Hashmap 到 ArrayList 的 For 循环没有保存正确的值。怎么修?

For loop of Hashmap to ArrayList is not holding the correct values. How to fix?

我有以下代码,但令人惊讶的是它不起作用;

     needsInfoView = (ListView) findViewById(R.id.needsInfo);
            needsInfoList = new ArrayList<>();
            HashMap<String, String> needsInfoHashMap = new HashMap<>();

            for (int i = 0; i < 11; i++) {
                needsInfoHashMap.put("TA", needsTitleArray[i]);
                needsInfoHashMap.put("IA", needsInfoArray[i]);
                Log.e("NIMH",needsInfoHashMap.toString());
//Here, I get the perfect output - TA's value, then IA's value
                needsInfoList.add(needsInfoHashMap);
                Log.e("NIL",needsInfoList.toString());
//This is a mess - TA, IA values for 12 entries are all the same, they are the LAST entries of needsTitleArray and needsInfoArray on each ArrayList item.

                needsInfoAdapter = new SimpleAdapter(getBaseContext(), needsInfoList,
                        R.layout.needsinfocontent, new String[]{ "TA", "IA"},
                        new int[]{R.id.ta, R.id.ia});
                needsInfoView.setVerticalScrollBarEnabled(true);
                needsInfoView.setAdapter(needsInfoAdapter);
            }

请查看日志行下方的评论。这解释了我收到的输出。如何通过 SimpleAdapter 将 ArrayList 值传递到我的 ListView 中的两个文本字段?

谢谢

您将同一个 HashMap 实例多次添加到 List,这意味着您在每次迭代中放入 Map 的条目将替换上一次迭代放入的条目.

您应该在每次迭代时创建一个新的 HashMap 实例:

for (int i = 0; i < 11; i++) {
    HashMap<String, String> needsInfoHashMap = new HashMap<>();
    needsInfoHashMap.put("TA", needsTitleArray[i]);
    needsInfoHashMap.put("IA", needsInfoArray[i]);
    needsInfoList.add(needsInfoHashMap);
    ....
}

For loop of Hashmap to ArrayList is not holding the correct values

因为您要在 needsInfoList

中添加相同的实例 HashMap

您需要在 needsInfoList 列表中添加新实例 HashMap,如下面的代码

另外 你需要在循环外设置你的 needsInfoAdapter 到你的 needsInfoView listview 就像下面的代码

试试这个

needsInfoList = new ArrayList<>();
needsInfoView = (ListView) findViewById(R.id.needsInfo);

  for (int i = 0; i < 11; i++) {
       HashMap<String, String> needsInfoHashMap = new HashMap<>();
       needsInfoHashMap.put("TA", needsTitleArray[i]);
       needsInfoHashMap.put("IA", needsInfoArray[i]);
       needsInfoList.add(needsInfoHashMap);
   }
   needsInfoAdapter = new SimpleAdapter(getBaseContext(), needsInfoList,
                R.layout.needsinfocontent, new String[]{"TA", "IA"},
                new int[]{R.id.ta, R.id.ia});
   needsInfoView.setVerticalScrollBarEnabled(true);
   needsInfoView.setAdapter(needsInfoAdapter);