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:

  1. in of screens, there no issue on add() or addall() functions, screens, if made change on list a2 affects a1 list.
  2. in these particular screens, clone concept (implements cloneable interface) used rid , working fine.

according study, add() functions sets reference destinations list.

my doubts are:

  1. why clone() required (for cases , not in all)?
  2. what happens if add() or addall() list list?
  3. whether, clone() mandatory add() or addall() methods or not?
  4. where should use clone() , shouldn't?
  5. what should happen list a1 if made changes in list a2?

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

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -