Java ArrayList Copy Changing Original Value -
i have copied arraylist
want keep original values of source arraylist
.
if change first item of source arraylist
, automatically chnages first item value of new arraylist
.
i used few code blocks couldn't solve problem.
arraylist<sicilbakiye> resultcopy = new arraylist<sicilbakiye>(); resultcopy.addall(result); // 1.method resultcopy=result.clone(); // 2.method resultcopy=result; // 3.method
if change :
result.get(0).setid(5);
this automatically changes :
resultcopy.get(0).getid() // return 5
how can solve ? ideas
let's have @ 3 methods provided , address problem:
arraylist resultcopy = new arraylist();
resultcopy.addall(result); // 1.method
this creates empty array list , adds elements result
copy. change result
(e.g. adding new element or removing one) not reflected in copy.
resultcopy=result.clone(); // 2.method
that same above, @ least of standard implementation used - copy created inside of clone()
, returned.
resultcopy=result; // 3.method
this assigns instance result
references resultcopy
, i.e. have 2 references same list. change made result
reflected resultcopy
, vice versa.
now actual problem:
result.get(0).setid(5);
does not change result
element inside result
. see change in resultcopy
.
it's same if put 2 courses @ school. if leave 1 you'll still in other , vice versa. if age changes (which ;) ) teacher in each course same answer.
what you're after called deep copy: copy list elements inside list. if reference other objects might have copy them - stop depends on requirements , structure of objects.
to create deep copies of objects either implement , call clone()
needed, use library clones via reflection (e.g. apache commons beanutils) or use mapping library (e.g. dozer, mapstruct, etc.).
Comments
Post a Comment