I have following LinkHashMap,
LinkedHashMap<String, ArrayList<String>> test1=new ...
in a loop I assign the key value pairs like this,
ArrayList<String> temp=new ...
//start iteration
temp.add("some strings")
test1.put("some string", temp);
temp.clear()//temp is cleared for next iteration
here temp is a temporary list I create just before and add something to it.
But the problem is that when I clear temp, the temp passed to test1 is also cleared, that means it is copied by reference. How can I use temp inside test1 still maintaining its reference. I know it is a basic concept, but i am new to java and did not get through all its features.
That’s because you are not really copying the
List,temp. You are copying the pointer (“reference” in Java lingo).There are two simple solutions here:
Listusingnew ArrayList<String>(temp)as what you store in the map.temp.clear(), dotemp = new ArrayList<String>().The second option is going to perform the best because it’s not making a copy of anything; it’s simply replacing the reference with a fresh
ArrayList.