[ACCEPTED]-All elements of An ArrayList change when a new one is added?-reference

Accepted answer
Score: 26

I've seen folks report this kind of problem 19 many times, and it always comes down to 18 this: you're actually not creating a new instance, but 17 instead using the same one for each iteration 16 of the loop. It's an easy mistake to make, especially 15 if you're coming from a language with different 14 copy semantics. There are a number of different 13 ways you can make this mistake; if you edit 12 your question to show the loop code, I'm 11 sure I'll be able to explain what's happening.

OK, now 10 that you've added the code: the problem 9 is that in "Content", all the data member 8 are marked "static". In Java, that means 7 that there's one variable shared by all 6 objects -- i.e., the variable has the same 5 value for every object. SO in fact you are creating 4 many Content objects to put in the ArrayList, but 3 they all look identical! Remove those "static" attributes 2 from Content's data members, and you'll 1 be all set.

Score: 17

ArrayList just stores reference of elements. Ensure 1 that your code looks like:

ArrayList list = new ArrayList<>();
loop(...) {
    MyObject newOne = new MyObject();
    newOne.setXXX(xxx);
    list.add(newOne);
}

Wrong code:

ArrayList list = new ArrayList<>();
MyObject sameOne = new MyObject();
loop(...) {
    sameOne.setXXX(xxx);
    list.add(sameOne);
}

More Related questions