i am trying to store arraylist in hashmap using put method.I cleard the list in next step to add next set of values in next iteration. Once the list is cleared, the value in the map is also getting cleared. Though I have put the list in map before clearing it.
HashMap map=new HashMap();
ArrayList list=new ArrayList();
list.add("value1");
list.add("value2");
map.put(key,list);
list.clear();
system.out.println("map");
sysout prints {key=[]}
someone please get me clear on how to persist the hashmaphash map.
You put a reference to the ArrayList in the Map, so when you clear that list, the list inside the Map is also cleared (since it's the same List).
If you want to initialize another List, you should create a new ArrayList instead of clearing the one you added to the Map.
HashMap map=new HashMap();
ArrayList list=new ArrayList(); // create first list
list.add("value1");
list.add("value2");
map.put(key1,list); // put first list in map
list=new ArrayList(); // create second list
list.add("value3");
map.put(key2,list); // put second list in map
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With