Sivaraj Eee
Sivaraj Eee

Reputation: 51

storing Arraylist in hashmap

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.

Upvotes: 3

Views: 448

Answers (2)

Pablo
Pablo

Reputation: 3011

You are putting the entire list as an element in the hash, when you clear the list, the only value in the hash is the empty list.

Upvotes: 1

Eran
Eran

Reputation: 394086

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
...

Upvotes: 1

Related Questions