Let's have a look at the 3 methods you provided and then address your problem:
ArrayList resultCopy = new ArrayList();
resultCopy.addAll(result); // 1.method
This creates an empty array list and adds all elements from result
to the copy. Any change to result
itself (e.g. adding a new element or removing one) is not reflected in the copy.
resultCopy=result.clone(); // 2.method
That basically does the same as above, at least of the standard implementation is used - just that the copy is created inside of clone()
and then returned.
resultCopy=result; // 3.method
This just assigns the instance that result
references to resultCopy
, i.e. you have 2 references to the same list. Thus any change made to result
is reflected by resultCopy
and vice versa.
Now to your actual problem:
result.get(0).setid(5);
does not change result
but the element inside result
. Thus you also see that change in resultCopy
.
It's the same as if I put you into two courses at school. If you leave one you'll still be in the other and vice versa. But if your age changes (which it will ;) ) the teacher in each course will get the same answer.
What you're probably after is called a deep copy: you copy the list as well as the elements inside the list. If those reference other objects you might have to copy them as well - where to stop depends on your requirements and the structure of your objects.
To create deep copies of your objects you could either implement and call clone()
where needed, use a library that clones via reflection (e.g. Apache Commons BeanUtils) or use a mapping library (e.g. Dozer, Mapstruct, etc.).