0

I have a simple class with only one String field and I have ArrayList. When I do for loop to add some elements to ArrayList something strange happeneds.

ArrayList<MyClass> list = new ArrayList<Myclass>();
MyClass mc = new MyClass();

for(int i=0;i<someNumber;i++){
     String s = new String(Integer.toString(i));
     mc.setString(s);
     list.add(mc);
}

After this, when I print my list, the string for every element from the list is same.

I understand that if I do list.add(new Myclass(s); works correctly but do I need to create a new instance of MyClass every time? If someNumber is large it takes too much memory. Thanks

  • You just mutate the same `mc` created before entering the loop, and repeatedly add it into the list. So after all it contains multiple references to one object (still `mc`) which has `string` property as the latest assigned. – Alex Salauyou Mar 03 '16 at 16:22

2 Answers2

3

You are re-adding the same element to the list. Try:

List<MyClass> list = new ArrayList<>(someNumber);


for(int i=0;i<someNumber;i++){
     String s = new String(Integer.toString(i));
     MyClass mc = new MyClass();  // create new object mc 
     mc.setString(s);
     list.add(mc); // add the new object to the list
}

By the same object I mean the same pointer to the object, you must create new pointer (initialize new class) to add it to the list as separate instance. In this case you were setting different value in setString on the same object and multiplicating the object in the list.

agilob
  • 6,082
  • 3
  • 33
  • 49
2

You need to move the instantiation of the object mc inside the loop.

ArrayList<MyClass> list = new ArrayList<Myclass>();


for(int i=0;i<someNumber;i++){
     MyClass mc = new MyClass();
     String s = new String(Integer.toString(i));
     mc.setString(s);
     list.add(mc);
}
raven
  • 2,381
  • 2
  • 20
  • 44