Skip to content Skip to sidebar Skip to footer

After Arraylist.add() In A Loop, All Elements Are Identical. Why?

If I do this [quasi-java-code]: while (loop) { localObject = getDataForObject(); globalPublicStaticArrayList.add(localObject); } All the elements in globalPu

Solution 1:

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.

Solution 2:

globalPublicStaticArrayList<Object>.add(localObject);

here you are passing the localObject reference. You you want a copy of every objects you should create a new object at every iteration

Solution 3:

In getDataForObject() may be you are not creating "new" object of return type. Because of that all objects are pointing to same address.

Post a Comment for "After Arraylist.add() In A Loop, All Elements Are Identical. Why?"