好的,这是代码,然后讨论如下:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码应该做什么?我想要做的是加载一个数组作为一些包装器对象的成员(在我们的例子中是TestWrapperObject).当我离开循环时,probModel ArrayList具有它应该具有的元素数量,但是所有元素都具有相同的最后一个元素的值(大小为10的数组,每个项目等于9).循环中不是这种情况.如果使用原始int值执行相同的"实验",一切正常.我自己错过了关于数组作为对象成员的东西吗?或者我刚刚遇到Java错误?我使用的是Java 6.
您只是创建一个currentRow数组实例.在行循环中移动它,它应该表现得更像你期望的.
具体来说,赋值in setCurrentRow不会创建对象的副本,而只会分配引用.因此,包装器对象的每个副本都将保存对同一int[]数组的引用.更改该数组中的值将使所有其他包装器对象的值看起来更改,这些包装器对象包含对该数组的同一实例的引用.
| 归档时间: |
|
| 查看次数: |
324 次 |
| 最近记录: |