【发布时间】:2014-07-20 12:56:51
【问题描述】:
这是我的代码。
public class Test {
public static void main(String[] args) {
ArrayList<Integer> temp = new ArrayList<Integer>();
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
int serialno = 0;
for (int i = 1000; i < 1004; i++) {
temp.clear();
temp.add(i);
temp.add((i+1000));
map.put(serialno++, temp);
}
System.out.println(map);
}
}
我希望输出是
{0=[1000, 2000], 1=[1001, 2001], 2=[1002, 2002], 3=[1003, 2003]}
但我得到的输出为
{0=[1003, 2003], 1=[1003, 2003], 2=[1003, 2003], 3=[1003, 2003]}
这里发生了什么。?我哪里做错了?
【问题讨论】:
-
您正在重用相同的哈希图,因此显然任何序列号的值都是相同的。
-
当您将对象
put放入地图(或列表)时,对象不会被复制。而是将对象的“引用”(指针)放入 Map 中。
标签: java collections arraylist hashmap