dcsimg
ArrayList and HashMap
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Rajneesh_Garg
Posted On:   Monday, February 11, 2002 10:14 PM

Hi, I have experienced a strange behavour with ArrayList and HashMap. My ArrayList contains a number of HashMap objects. ArrayList list = new ArrayList(); HashMap map = new HashMap(3); for(int i=0;i <10;i++){ map.put(key1,value1); map.put(key2,value2); map.put(key3,value3); list.add(map); map.clear() } As a result of this code, the List object contains 10 null HashMap objects. If I remove map.clear(), and change the code to following, it works fine: for(int i=0;i <10;i++){ map = new HashMap(3); map.put(key1,value1); map.put(key2,value2); map.put(   More>>

Hi,


I have experienced a strange behavour with ArrayList and HashMap.

My ArrayList contains a number of HashMap objects.

			
ArrayList list = new ArrayList();
HashMap map = new HashMap(3);

for(int i=0;i <10;i++){
map.put(key1,value1);
map.put(key2,value2);
map.put(key3,value3);

list.add(map);

map.clear()
}

As a result of this code, the List object contains 10 null HashMap objects.


If I remove map.clear(), and change the code to following, it works fine:
			
for(int i=0;i <10;i++){
map = new HashMap(3);
map.put(key1,value1);
map.put(key2,value2);
map.put(key3,value3);

list.add(map);

//map.clear();
map = null;
}

Now the List object contains all the 10 records. Any thoughts?

Rajneesh Garg

RGarg@Indiatimes.com    <<Less

Re: ArrayList and HashMap

Posted By:   AlessandroA_Garbagnati  
Posted On:   Tuesday, February 12, 2002 12:09 AM

Hi,

That's because you are inserting the reference to the map, and not a clone of the map.
About | Sitemap | Contact