ArrayList.clear even clears elements stored in a HashMap!
i came across a rather weird problem today,
ArrayList listOfCd=new ArrayList(); HashMap newHash= new LinkedHashMap(); for(int i=0;i<someThing.size();i++) { listOfCd.clear(); //if same key has been processed before //append the values to the old List if(newHash.containsKey(key)) { listOfCd=(ArrayList)newHash.get(key); } listOfCd.add(some data); newHash.put(key,listOfCd); }
this is the logic i use to store some list in a HashMap,
what happened was, the HashMap contained the same list for all the key`s! this baffled me for quite some time untill i saw the list.clear(), it turns out the list.clear() clears all the elements previously stored in the HashMap as well! since arrayList uses only references to store Data.
be careful when you use list.clear() next time!
About this entry
You’re currently reading “ArrayList.clear even clears elements stored in a HashMap!,” an entry on Quality Obsessed
- Published:
- 06.27.08 / 7am
- Category:
- Java
- Rate article:
Printer Friendly

No comments
Jump to comment form | comments rss [?] | trackback uri [?]