ArrayList<Integer> a =new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> j =new ArrayList<ArrayList<Integer>>();
a.add(1);
a.add(2);
a.add(3);
for(int c=0; c<10; c++){
j.add(a);
}
j.get(3).add(1);
System.out.println(j);
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么这个代码为j的每个元素添加1而不是只有第三个元素,我该怎么做才能解决这个问题?
use*_*460 11
这是添加1到数组列表时发生的情况a.
所以基本上所有10个ArrayList索引都j指向一个ArrayList a.因此,从任何索引打印值j将始终给您相同的结果.
让每个索引指向不同的数组列表:
| 归档时间: |
|
| 查看次数: |
5311 次 |
| 最近记录: |