Writing to the wrong class instance in java -


note: code work in progress solution assignment in discrete optimization pascal van hentenryck on coursera. of not want see possible solutions or hints might not want read further.

i new java might totally wrong code. have spent while on code no progress. stepping through code in eclipse.

when step through code below trying update instance of branch[0] when update branch[0].path thisnode.path gets updated , when update branch[1].path branch[0].path , thisnode.path gets updated (at-least watch window shows).

what doing wrong here ?

void iterateonestep(bnbnode thisnode, int next_path){     bnbnode [] branch;      branch = new bnbnode [2];      //item not picked     branch[0] = new bnbnode(items.size());     branch[0].availablecapacity = thisnode.availablecapacity;     branch[0].path = thisnode.path;     branch[0].path[next_path] = 0;     branch[0].val = thisnode.val;     //item picked     branch[1] = new bnbnode(items.size());     branch[1].availablecapacity = thisnode.availablecapacity - items.get(next_path).weight;     branch[1].path = thisnode.path;     branch[1].path[next_path] = 1;     branch[1].val = thisnode.val+items.get(next_path).value;     .............. 

the class bnbnode

public class bnbnode {     int[] path;     int val;     int availablecapacity;     int potentialval;     int optimum;      bnbnode(int numitems) {         path = new int[numitems];         numitems--;         while (numitems >= 0) {             path[numitems] = -1;             numitems--;         }         val = 0;         optimum = 0;     } } 

the full code @ https://github.com/vinaysamuel/knapsack/tree/master/src

thanks time, vinay

look @ these bits of code:

branch[0].path = thisnode.path; ... branch[1].path = thisnode.path; 

the type of path int[], means you're copying references. you've got single array object, , after code above, of branch[0].path, thisnode.path , branch[1].path refer single array.

you may wish clone array create independent copies:

branch[0].path = thisnode.path.clone(); ... branch[1].path = thisnode.path.clone(); 

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -