【问题标题】:Not Allowing change the hashmap value after adding in arraylist添加到arraylist后不允许更改hashmap值
【发布时间】:2014-07-09 10:36:36
【问题描述】:

我有这个数组列表和另一个用于 hashmap 的

 ArrayList<HashMap<String, String>> agentList = new ArrayList<HashMap<String, String>>();
 HashMap<String, String> agentproperty = new HashMap<String, String>();

我收到了来自 php 文件的 jArray。并尝试使用 hashmap 将其放入数组中。

 JSONArray jArray = jsonObj.getJSONArray(TAG_AGENT);
      String id = null;
      String name = null;

        for (int i = 0; i < jArray.length(); i++) {
            JSONObject a = jArray.getJSONObject(i);
            id = a.getString(TAG_AGENTID);
            name = a.getString(TAG_NAME);

            agentproperty.put("AGENTID", id);
            agentproperty.put("NAME", name);

            Log.d("id",id);
            Log.d("name",name);
            agentList.add(agentproperty);


    }
                Log.d("firstperson",String.valueOf(agentList.get(0)));
                Log.d("secondperson",String.valueOf(agentList.get(1)));

我可以得到

id 1, hame cathy; id 2, name john

用于日志内部循环。但是从最后的日志中,我得到了

id 2,名字约翰; ID 2,姓名约翰 即使添加了arraylist,似乎agentproperty的值也发生了变化。 我尝试使用 agentList.add(agentproperty);循环外。没用。仅插入最后一个值(id 2,名称 john)。知道如何用从循环中获得的所有值填充这个数组。我需要在 listview 中使用 agentList。

【问题讨论】:

  • 确保您拥有唯一的 id

标签: java php android arraylist hashmap


【解决方案1】:

是的。您必须在每次迭代时创建 HashMap 的新实例,否则如果条目已存在,您将覆盖给定键的值

【讨论】:

  • 在每次迭代中,您都会覆盖“AGENTID”和“NAME”的值,因为这是 HashMap 的工作方式。如果它确实检查它是否有密钥条目。如果有,只需将值替换为您提供的最后一个值,否则它将创建一个新条目。
  • Excellent.Instantiation inside loop,这就是所需要的。谢谢
【解决方案2】:

移动

HashMap<String, String> agentproperty = new HashMap<String, String>();

for 循环内

【讨论】:

  • 谢谢。有效。这是小问题。但令人兴奋。
猜你喜欢
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 2012-03-23
  • 1970-01-01
相关资源
最近更新 更多