Java Copy

 1 Copy Object in java


Use = for immutable class ex: Integer , String or Wrapper classes Object
 

Use Contructor has paramater copy, ObjectA(ObjectA ob) if ObjectA only has field is immutable class


Use Interface Cloneable with class has propeties Object reference example: (User has properties Address) 


Use library Apache Common Lang SerializationUtils.clone(object) with class implements Serializable 


https://github.com/nguyenthinhit996/sharefullcode/blob/master/Learn%20Java/Java%20Basic/ListCollection/src/copies/objects/ObjectDemo.java

 

2 Copy List in java

 

Use = , contructor, addAll, Collections.copy the contents of both lists will reference the same objects.

 

Using the constructor is good to copy immutable objects

 

Use clone for copy deep in list (use stream and map new object)


Note: 

When use = to copy, Edit and Delete effect on both list.
When use constructor (new List<> (ListOrigin)) to copy, Call Edit effect on both list but Call Delete on effect to list call method delete, not effect to list others.

view:  demoCopyAfterThatDeleteElement method


https://github.com/nguyenthinhit996/sharefullcode/blob/master/Learn%20Java/Java%20Basic/ListCollection/src/copies/collections/DemoCopyList.java


0 comments :

Post a Comment

Cancel Reply

About Me

My photo
Tân An, Long An, Vietnam
Hello everyone, I love programming, I love making friends with people all over the world.