You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将HashMap键值对转为子列表存入嵌套List及代码问题排查

问题原因

Java的对象操作基于引用传递,你在循环外仅实例化了一次tempList,后续所有对tempList的修改都是操作同一个内存地址的对象。当你调用nestedList.add(tempList)时,存入嵌套列表的只是这个对象的引用,而非内容拷贝。因此你每次执行tempList.clear()时,本质是清空了这个共用对象的内容,嵌套列表中所有指向该对象的引用对应的内容自然也会同步清空。

修复方案

你需要为每组键值对创建独立的List实例,避免多个元素共用同一个List引用,将tempList的实例化逻辑移到循环内部即可:

List<List<Integer>> nestedList = new ArrayList<>();
Map<Integer,Integer> map = new HashMap<>();
// 填充HashMap数据
map.put(3,1);
map.put(2,1);
map.put(1,1);

for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
    // 每次循环生成全新的临时List,互不干扰
    List<Integer> tempList = new ArrayList<>();
    tempList.add(entry.getKey());
    tempList.add(entry.getValue());
    nestedList.add(tempList);
}

如果你坚持要在循环外声明tempList,也可以在存入嵌套列表时传入内容拷贝,修改添加逻辑为nestedList.add(new ArrayList<>(tempList));即可。

内容的提问来源于stack exchange,提问作者calai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 13:24:03