Java的:创建HashMaps这样的列表 [英] Java: create a list of HashMaps

查看:132
本文介绍了Java的:创建HashMaps这样的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建的地图列表。在下面的code,我期待获得

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}]

如何避免覆盖第一张地图?这里是我的code:

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学习者,我花了好几个小时来学习和试验数组列表,链表,地图,LinkedMap等---我coldn't得到它的工作。我不与我有限的知识,为什么不懂。现在,这些如下回答都是极好的!他们在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(新的HashMap()); 作为,增加了一个空映射到列表中是从来没有填充的

also, you can remove the list.add(new HashMap()); as that adds an empty map to your list that is never populated.

这篇关于Java的:创建HashMaps这样的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆