I got some problem with reference assignment in java.
Let me explain: in my code, i’m using an ArrayList of BooleanWrap (a home made class of boolean) which will be later assigned as a value in a HashMap (there is a for cycle which update the values of this ArrayList until a condition is verified).
Something like this:
ArrayList<BooleanWrap> temp=new ArrayList <BooleanWrap>(48);
//cycle: operations to fill the ArrayList, then a condition is satisfied
hashMap.put(index, temp);
After that, I have to reuse the temp variable, so I need to reinitialize it. I do it with the following instructions:
for(BooleanWrap bool: temp){
bool.set(false);
}
There comes my problem: assigning temp as a value of the hashMap will save only the reference of the variable, not the actual value.
So, reinitializing temp cause also the updating inside the hashmap (in this case, setting everything false).
Now, I think that even with clone() method I should get the same result (cause it produces a shallow copy of the ArrayList).
Is there a way to reuse the same variable temp in my cycle without assign later the reference of it to the hashmap?
Actually I can do it with a method which creates a deep copy of the arraylist:
public static ArrayList<BooleanWrap> deepcopy(ArrayList<BooleanWrap> original){
ArrayList<BooleanWrap> copy=new ArrayList<BooleanWrap>(48);
for(BooleanWrap bool: original)
copy.add(new BooleanWrap (bool.get()));
return copy;
}
but I need something done inline, without any other methods and as shorter as it can be.
Any advice/suggestion/insult?
That does not re-initialize the temp variable. That re-initializes the contents of your temp variable. to re-initialize the temp variable your code would look like