好的,这是代码,然后讨论如下:
public class FlatArrayList {
private static ArrayList<TestWrapperObject> probModel = new ArrayList<TestWrapperObject>();
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] currentRow = new int[10];
int counter = 0;
while (true) {
for (int i = 0; i < 10; i++) {
currentRow[i] = probModel.size();
}
TestWrapperObject currentWO = new TestWrapperObject(currentRow);
probModel.add(counter, currentWO);
TestWrapperObject testWO = probModel.get(counter);
// System.out.println(testWO);
counter++;
if (probModel.size() == 10) break;
}
// Output the whole ArrayList
for (TestWrapperObject wo:probModel) {
int [] currentTestRow = wo.getCurrentRow();
}
}
}
public class TestWrapperObject {
private int [] currentRow;
public void setCurrentRow(int [] currentRow) {
this.currentRow = currentRow;
}
public int [] getCurrentRow() {
return this.currentRow;
}
public TestWrapperObject(int [] currentRow) {
this.currentRow = currentRow;
}
}上面的代码应该做什么?我要做的是加载一个数组作为某个包装器对象(在我们的例子中是TestWrapperObject)的成员。当我离开循环时,probModel ArrayList的元素数与它应该拥有的元素数相同,但是所有元素的值都与最后一个元素的值相同(一个大小为10的数组,每个元素都等于9)。循环中的情况并非如此。如果你用一个原始的int值执行同样的“实验”,一切都很好。我自己是不是遗漏了什么,把数组当作对象成员?或者我只是遇到了一个Java bug?我使用的是Java 6。
发布于 2009-01-25 18:12:49
您仅创建了currentRow数组的一个实例。将其移动到row循环中,它的行为应该更符合您的预期。
具体地说,setCurrentRow中的赋值不会创建对象的副本,而只是赋值引用。因此,包装器对象的每个副本都将包含对同一个int[]数组的引用。更改该数组中的值将使持有对该数组的同一实例的引用的所有其他包装对象的值看起来也发生了更改。
发布于 2009-01-25 19:36:29
我不想听起来居高临下,但请始终记住优秀的pragmatic programmer书中的技巧26。
select未损坏
发现java bug是非常罕见的。记住这一点通常会帮助我重新检查我的代码,把它转过来,抖动那些松散的部分,直到我最终发现我错在哪里。当然,尽早寻求帮助也是非常受鼓励的:)
https://stackoverflow.com/questions/478006
复制相似问题