我想保存数组列表中的所有int []数据,这样我就可以逐步看到每件事。只有我的问题是它覆盖了我的ArrayList中已经存在的int []。 如何填充我的数组列表而不覆盖ArrayList中的旧int?
ArrayList<int[]> lijstje = new ArrayList<int[]>();
public int[] data = {7,4,8,56,67,85,23,65,23,65,23,22};
int stemp;
int len = 10;
public void shellSort(){
while (h <= len / 3) {
h = h * 3 + 1;
}
while (h > 0) {
for (outer = h; outer < len; outer++) {
stemp = data[outer];
inner = outer;
while (inner > h - 1 && data[inner - h] >= stemp) {
data[inner] = data[inner - h];
inner -= h;
}
data[inner] = stemp;
lijstje.add(data);
}
h = (h - 1) / 3;
}
}
答案 0 :(得分:3)
数组存储为引用,因此当您将数组更改为一个位置时,您直接存储的任何位置都会更改为。相反,创建一个具有相同值的全新数组,并存储它。要做到这一点,请执行array.clone(),以便
ArrayList<int[]> lijstje = new ArrayList<int[]>();
public int[] data = {7,4,8,56,67,85,23,65,23,65,23,22};
int stemp;
int len = 10;
public void shellSort(){
while (h <= len / 3) {
h = h * 3 + 1;
}
while (h > 0) {
for (outer = h; outer < len; outer++) {
stemp = data[outer];
inner = outer;
while (inner > h - 1 && data[inner - h] >= stemp) {
data[inner] = data[inner - h];
inner -= h;
}
data[inner] = stemp;
lijstje.add(data.clone()); // Notice here how it's data.clone() instead of just data
}
h = (h - 1) / 3;
}
}
这是一个显示如何通过引用传递数组的示例,这个
int[] original = { 1, 2, 3 };
int[] passedByReference = original;
int[] cloned = original.clone();
System.out.println("Before:");
System.out.println(Arrays.toString(original));
System.out.println(Arrays.toString(passedByReference));
System.out.println(Arrays.toString(cloned));
original[0]=10;
System.out.println("After:");
System.out.println(Arrays.toString(original));
System.out.println(Arrays.toString(passedByReference));
System.out.println(Arrays.toString(cloned));
将具有以下输出
Before:
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
After:
[10, 2, 3]
[10, 2, 3]
[1, 2, 3]
正如您所看到的,克隆的一个不受影响,而原始的和通过引用的那个是。在您的代码中,您不希望更改原始文件以影响您存储的数组,因此您必须以某种方式克隆它(对于2D数组,array.clone()是一种很简单的方法)。