LinkedHashMap vs ArrayList.clear()
Hi All, I need a help on my code.
I have put an arraylist as a value in to a map.But when I cleared the arraylist the value of map also removed. and after clear the arraylist when I put same arraylist with new entry and put on map for different key it behave unexpectedly.
please suggest me on this.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
public class fullTest1
{
public static void main(String[] args)
{
LinkedHashMap<String, List> hashMap = new LinkedHashMap<String, List>();
ArrayList<String> arrlist1 = new ArrayList<String>();
arrlist1.add("a");
arrlist1.add("b");
arrlist1.add("c");
arrlist1.add("d");
hashMap.put("1", arrlist1);
System.out.println("Map Before ArrayList clear:"+hashMap);
arrlist1.clear();
System.out.println("Map After ArrayList clear:"+hashMap);
arrlist1.add("a");
hashMap.put("2", arrlist1);
System.out.println("Map with new Key:"+hashMap);
}
}
-----------
Out Put is:
Map Before ArrayList clear:{1=[a, b, c, d]}
Map After ArrayList clear:{1=[]}
Map with new Key:{1=[a], 2=[a]}
Re: LinkedHashMap vs ArrayList.clear()
putting in hash map puts reference to original object, not deep copy of it, so any changes to object itself will propagate to objects retrieved from hash map
Re: LinkedHashMap vs ArrayList.clear()
Thanks for reply; I tried to put the clone of ArrayList as following and it working as expected.
But is it the only way or there are any other way I can do. please suggest me.
hashMap.put("1", (List) arrlist1.clone());
Instead of
hashMap.put("1", arrlist1);
-----------
out put is:
Map Before ArrayList clear:{1=[a, b, c, d]}
Map After ArrayList clear:{1=[a, b, c, d]}
Map with new Key:{1=[a, b, c, d], 2=[a]}
Re: LinkedHashMap vs ArrayList.clear()
Quote:
But is it the only way or there are any other way I can do. please suggest me.
You can also do:
Code:
hashMap.put("1", new ArrayList(arrlist1));