HashMap.put()覆盖已经存在的值,即使Key值不同也是如此

时间:2016-04-28 05:44:30

标签: java android string hashmap

之前已经提出过这个问题。但是这些回复中的任何一个都没有解决我的问题。有人请帮忙。

我有两个HashMaps, final HashMap<String,String> dataList = new HashMap<String,String>(); final HashMap<String,HashMap<String,String>> full = new HashMap<String,HashMap<String,String>>();

这是我的代码。

            int i=0;
            for(DataSnapshot snap : dataSnapshot.getChildren()) {
                i++;
                String id = "Name "+String.valueOf(i);
                strArray.add(snap.child("email").getValue().toString());
                String name =          snap.child("FirstName").getValue().toString() + " " + snap.child("LastName").getValue();
                dataList.put("Name", name);
                dataList.put("Email",snap.child("email").getValue().toString());
                dataList.put("Mobile", snap.child("Mobile").getValue().toString());
                dataList.put("Birthdate", snap.child("birthdate").getValue().toString());
                System.out.println("Datalist " + dataList);
           full.put(id, dataList);}

我希望有{Name 1 = {Birthdate=2012/02/15, Email=gwcsathsara@gmail.com, Mobile=, Name= },Name 2 = {Birthdate=2012/02/15, Email=xc, Mobile=8524, Name=Sdcc Kkn}}

但它超越了这个强大的价值。这是我得到的结果, {Name 1={Birthdate=2012/02/15, Email=xc, Mobile=8524, Name=Sdcc Kkn}, Name 2={Birthdate=2012/02/15, Email=xc, Mobile=8524, Name=Sdcc Kkn}}

有人请帮我解决这个问题。如果您需要更多信息,请评论。 谢谢

1 个答案:

答案 0 :(得分:6)

您需要在此行之前添加以下行:HashMap<String,String> dataList = new HashMap<String,String>();dataList.put("Name", name);

正在发生的事情是您正在重新使用Map,因此您每次都会覆盖密钥,最终结果是您处理的最后一个孩子。

相关问题