【问题标题】:HashMap.put() Override already excisting value even the Key value is differentHashMap.put() 覆盖已经存在的值,即使 Key 值不同
【发布时间】:2016-08-22 17:13:43
【问题描述】:

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

我有两个 HashMap, 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}}

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

【问题讨论】:

  • 每次循环都使用相同的Map 实例。每次为dataList 创建一个新的Map 实例。

标签: java android string hashmap


【解决方案1】:

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

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

【讨论】:

  • 嘿,非常感谢。我没有意识到这一点。再次感谢。
猜你喜欢
  • 2021-07-09
  • 2015-05-10
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
相关资源
最近更新 更多