java - When to use clone() and how actually addAll() and add() works -
i using java mysql.
there 60 transactions screens there in project. had used add() , addall() functions copy arraylist.
for example:
list<bean> a1 = new arraylist<bean>(); // , add value list<bean> a2 = new arraylist<bean>(); a2.addall(a1); in case:
- in of screens, there no issue on
add()oraddall()functions, screens, if made change on lista2affectsa1list. - in these particular screens, clone concept (implements
cloneableinterface) used rid , working fine.
according study, add() functions sets reference destinations list.
my doubts are:
- why
clone()required (for cases , not in all)? - what happens if
add()oraddall()list list? - whether,
clone()mandatoryadd()oraddall()methods or not? - where should use
clone(), shouldn't? - what should happen list
a1if made changes in lista2?
my final question:
when use clone() or copy constructor , when need not use. , in generic list, should happen source list if made changes in target list above example.
yes, addall adds references of source list target list. doesn't create copies of instances these references refer to.
this sufficient when list holds references immutable objects. if add or remove elements 1 of lists after addall operation, changes won't reflected in other list.
if list holds references mutable objects, , modifying state of objects, must create copies (either using clone or copy constructor) if don't want changes in 1 list reflected in other list.
btw, passing list add (instead of addall) add reference of list target list. unless target list list of lists, shouldn't that. add should accept single element added list.
Comments
Post a Comment