Java:创建一个 HashMap 列表 [英] Java: create a list of HashMaps
问题描述
我尝试创建地图列表.在下面的代码中,我希望得到 p>
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}]
然而,我只得到了
[{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 );
谢谢!
============================
==========================
作为一个过程语言背景 (SAS) 的 Java 学习者,我花了相当多的时间学习和实验 ArrayList、LinkedList、Map、LinkedMap 等——我不知道它是否能够工作.我不明白为什么以我有限的知识.现在,以下这些答案都很棒!他们解释了 Java 中非常重要的数据结构,至少对我来说是这样.
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.
谢谢大家!!!!
推荐答案
您需要为每个条目创建一个新的 HashMap,而不是重用现有的.这会起作用:
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);
此外,您可以删除 list.add(new HashMap());
因为这会向您的列表中添加一个从未填充的空映射.
also, you can remove the list.add(new HashMap());
as that adds an empty map to your list that is never populated.
这篇关于Java:创建一个 HashMap 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!