Reputation: 163
If I add an object to an ArrayList in Java, I add a reference to it, right? So assume this situation. I create an object called obj and set it to a value. I then loop a certain amount of times and each time I modify obj a little (like change its position) and then add it to the ArrayList. After each sequence of the loop I reset obj to the default value so the next sequence will have a fresh obj to modify. Assuming I had been passing references of obj all the time, everything in the ArrayList will be set to the default value also? From testing I see that the values don't change and are all different, which I find strange. Could somebody elaborate?
Block b = block.clone();
for(int x = 0; x < amountX; x++){
Vector3f offset = new Vector3f(0, 0, 0);
offset.x = x * block.getScale().x;
for(int y = 0; y < amountY; y++){
offset.y = y * block.getScale().y;
for(int z = 0; z < amountZ; z++){
offset.z = z * block.getScale().z;
b.move(offset);
addBlocks(b);
b = block.clone();
}
}
}
for(Block a : blocks)
System.out.println(a.getPosition());
addBlocks adds a block to the ArrayList. The last loop prints out all different positions. Block.clone() just creates a new block with the same parameters.
Upvotes: 4
Views: 148
Reputation: 8246
Object o = new Object();
At this point you are not modifying the object any more, you are modifying the reference. i.e. creating a new object and pointing this variable at it.
do
{
Object o = new Object(); // set o to point to a new Object
arrayList.add(o); //add a reference to the new object to the ArrayList
}while(true)
the second time through this loop, the first object created in memory at pos1 say is referenced by arrayList[1]. But you then change where object o is pointing in memory by creating a new one (at pos2) and pointing to it with o. You now have two object in memory, one referenced at [1] in the arrayList and one referenced at object o.
If you modify the object and not the reference, you will get the behaviour you talk about, e.g.
do
{
g.setName("Steven");
arrayList.add(o);
}while(true)
Upvotes: 3