If I do this [quasi-java-code]:
while (loop)
{
localObject = getDataForObject();
globalPublicStaticArrayList<Object>.add(localObject);
}
All the elements in globalPublicStaticArrayList are identical, equal to the last copy of localObject added. I stepped thru the loop in the debugger and saw that as soon as an Object is added, it is copied in to all the elements of the globalPublicStaticArrayList.
The workaround I found is:
while (loop)
{
localObject = getDataForObject();
globalPublicStaticArrayList<Object>.add(new Object(localObject.member1, localObject.member2,...));
}
Has it something to do with pass-by-reference in Java? How come the elements are identical in the first case? Thanks.
Java uses call by value, but here those values are references to objects.
What you are adding to the list is not a copy of the object, but a copy of the reference. Your method returned the same object each time you called it. It probably should return a new object each time, then you wouldn’t need this workaround.