看看这个小例子
import java.util.ArrayList;
import java.util.HashMap;
public class Foo {
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<Integer>();
HashMap<String, ArrayList<Integer>> foo = new HashMap<String,ArrayList<Integer>>();
for (int i = 0; i < 20; i++)
array.add(i);
foo.put("1", array);
// array.clear();
System.out.println(foo.get("1").size());
}
}
现在,如果使用 array.clear()
它会自动删除与 hashmap 中指定键关联的 arrayList 的所有值
我怎样才能避免这种情况?
以这样的方式:
我可以执行
array.clear();
(在hashmap中输入值后)并且只删除ArrayList<Integer> array
的值与该键相关联的数组的值不会被删除在 HashMap 中
如果你启动这个程序,它将打印20而不使用array.clear();
, 0 而不是
最佳答案
它正在删除 map 键元素,因为它们是相同的对象。您必须进行浅拷贝才能使两个列表分开
虽然创建浅拷贝非常简单:
List<Integer> newList = new ArrayList<Integer>(oldList);
代码如下:
public class Foo {
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<Integer>();
HashMap<String, ArrayList<Integer>> foo = new HashMap<String, ArrayList<Integer>>();
for (int i = 0; i < 20; i++)
array.add(i);
ArrayList<Integer> newList = new ArrayList<Integer>(array);
foo.put("1", newList);
array.clear();
System.out.println(foo.get("1").size());
}
}
关于java - HashMap 和数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23473567/