This problem has two typical causes:
Static fields
If the objects in your list store data in static fields, each object in your list will look the same, since it contains the same values. Consider the class below:
public class Foo { private static int value;
In this example, there is only one int value that is used by all instances of Foo because it is declared as static . (See the “Understanding Class Members” textbook.)
If you add multiple Foo objects to the list using the code below, each instance will return 3 from the getValue() call:
for (int i = 0; i < 4; i++) { list.add(new Foo(i)); }
The solution is simple - do not use static keywords for fields in your class unless you really want the values to be shared between each instance of this class.
Adding the same object
If you add a temporary variable to the list, you must create a new instance of the object you add each time you loop. Consider the following piece of error code:
List<Foo> list = new ArrayList<Foo>(); Foo tmp = new Foo(); for (int i = 0; i < 3; i++) { tmp.setValue(i); list.add(tmp); }
Here the tmp object was created outside the loop. As a result, the same instance of the object is added to the list three times. The instance will contain the value 2 , because it was the value passed during the last call to setValue() .
To fix this, simply move the object's construction into a loop:
List<Foo> list = new ArrayList<Foo>(); for (int i = 0; i < 3; i++) { Foo tmp = new Foo();
Duncan Jones Nov 07 '13 at 18:11 2013-11-07 18:11
source share