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!!!!
HashMap mMap = new HashMap(); ArrayList list = new ArrayList(); list. add(new HashMap()); mMap. put("start",1); mMap. put("text","yes"); list.
A HashMap contains key-value pairs, there are three ways to convert a HashMap to an ArrayList: Converting the HashMap keys into an ArrayList. Converting the HashMap values into an ArrayList. Converting the HashMap key-value pairs into an ArrayList.
A Map is an object that maps keys to values or is a collection of attribute-value pairs. The list is an ordered collection of objects and the List can contain duplicate values. The Map has two values (a key and value), while a List only has one value (an element).
Something which is maybe also worth mention it, is that you should define the type of the elements you use in the List, for the HashMap its not possible because you are mixing Integers and Strings.
And another thing is that you should use the List interface as type, so you are able to change the implementation (ArrayList or whatever) in the future.
Here the corrected code:
Map mMap = new HashMap();
List<Map> list = new ArrayList();
You need to create a new HashMap for every entry, instead of reusing the existing one. This would work:
HashMap mMap = new HashMap();
mMap.put("start",1);
mMap.put("text","yes");
list.add(mMap);
mMap = new HashMap(); // create a new one!
mMap.put("start",2);
mMap.put("text","no");
list.add(mMap);
also, you can remove the list.add(new HashMap());
as that adds an empty map to your list that is never populated.
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