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