【发布时间】:2021-11-21 20:19:25
【问题描述】:
我正在尝试将 hashmap 键和值存储到一个列表中,然后将该列表嵌套在另一个列表中。所以像:
Hashmap 包含 - [ {3,1} , {2, 1}, {1,1} ]
我想分别将 {3,1}、{2, 1}、{1,1} 添加到 3 个不同的 List 中。
接下来,我会将这 3 个列表添加到一个外部列表中,将这 3 个列表嵌套在一个内部列表中。
但我想了解为什么下面的代码不起作用?我下面的嵌套列表将被引用到我不理解的 tempList。
List<Integer> tempList = new ArrayList<>();
List<List<Integer>> nestedList = new ArrayList<>();
Map<Integer,Integer> map = new HashMap<>();
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
tempList.clear(); //once it run this, nestedList will be cleared too. Why?
tempList.add(entry.getKey());
tempList.add(entry.getValue());
nestedList.add(tempList); //tempList will get referenced to nestedList
}
【问题讨论】:
标签: java list hashmap nested-lists