Ok, here is the code and then the discussion follows:
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; } }
What is the above code supposed to do? What I am trying to do is load an array as a member of some wrapper object (TestWrapperObject in our case). When I get out of the loop, the probModel ArrayList has the number of elements it is supposed to have but all have the same value of the last element (an array of size 10 with each item equal to 9). This is not the case inside the loop. If you perform the same ‘experiment’ with a primitive int value everything works fine. Am I missing something myself regarding arrays as object members? Or did I just encounter a Java bug? I am using Java 6.
You are only creating one instance of the
currentRowarray. Move that inside the row loop and it should behave more like you expect.Specifically, the assignment in
setCurrentRowdoes not create a copy of the object, but only assigns the reference. So each copy of your wrapper object will hold a reference to the sameint[]array. Changing the values in that array will make the values appear to change for all other wrapper objects that hold a reference to the same instance of the array.