I tried to create a list of maps. In the following code, I’m expecting to get
[{start=1,text=ye}, {start=2,text=no}]
however, I only got
[{start=2,text=no}, {start=2,text=no}]
How to avoid overriding the first map? Here is my code:
HashMap mMap = new HashMap();
ArrayList list = new ArrayList();
list.add(new HashMap());
mMap.put("start",1);
mMap.put("text","yes");
list.add(mMap);
mMap.put("start",2);
mMap.put("text","no");
list.add(mMap);
System.out.println("Final result: " + list );
thanks!
==========================
As a learner of Java who came from a procedure language background (SAS), I spent quite a few hours learning and experimenting ArrayList, LinkedList, Map, LinkedMap, etc— I coldn’t get it to work. And I don’t understand why with my limited knowledge. Now, these following answers are all excellent! They explained very important data structure in Java, at least for me.
THANK YOU ALL!!!!
You need to create a new HashMap for every entry, instead of reusing the existing one. This would work:
also, you can remove the
list.add(new HashMap());as that adds an empty map to your list that is never populated.