List interface does not enforce copy of added elements in the Javadoc, but ArrayList
and LinkedList
both copy them (if I understand the source code correctly).
So, am I safe to clear()
the added list in this code? I assume not?
@Test
void test() {
List<MyObject> original = new ArrayList<>();
original.add(new MyObject("John", 1));
original.add(new MyObject("David", 2));
List<MyObject> newList = new LinkedList<>(); // or ArrayList, both can pass the test, but not sure about other impl.
newList.addAll(original);
original.clear();
System.gc();
for (MyObject o: newList) {
assertThat(o, CoreMatchers.notNullValue());
}
}
In a code review and see such issue, the added list is cleared after addAll(), not sure about if I can let this pass.