Java中如何将ArrayList作为值存入HashMap并清空该ArrayList?
问题分析与解决方法
你遇到的核心问题是Java中集合是引用类型——当你把ArrayList存入HashMap时,HashMap保存的不是列表里的元素副本,而是这个ArrayList对象的内存引用。所以之后你清空原ArrayList,HashMap里对应的列表也会跟着变空;如果复用列表时不清空就添加新元素,所有键对应的都会是同一个列表,最后全是所有输入值。
下面给两种靠谱的解决方式:
方案1:每次存完后新建ArrayList复用
不需要清空,直接给tempList重新赋值一个新的ArrayList对象,这样每次存入HashMap的都是独立的列表:
HashMap<String, ArrayList<String>> dataMap = new HashMap<>(); ArrayList<String> tempList = new ArrayList<>(); // 处理第一个键 tempList.add("A值1"); tempList.add("A值2"); dataMap.put("键A", tempList); // 直接新建列表,原列表无需清空 tempList = new ArrayList<>(); // 处理第二个键 tempList.add("B值1"); dataMap.put("键B", tempList);
方案2:存入HashMap前先存列表副本
如果一定要复用同一个ArrayList对象,就在存入HashMap时,先创建当前列表的副本(比如用ArrayList的拷贝构造方法),再清空原列表:
HashMap<String, ArrayList<String>> dataMap = new HashMap<>(); ArrayList<String> tempList = new ArrayList<>(); // 处理第一个键 tempList.add("X值1"); // 把当前列表的副本存入HashMap dataMap.put("键X", new ArrayList<>(tempList)); // 清空原列表准备复用 tempList.clear(); // 处理第二个键 tempList.add("Y值1"); tempList.add("Y值2"); dataMap.put("键Y", new ArrayList<>(tempList)); tempList.clear();
这两种方式都能保证HashMap里每个键对应的都是独立的列表,不会互相干扰。
内容的提问来源于stack exchange,提问作者brago123
相关产品推荐
相关产品推荐

