Earlier we read Cloning in java using clone- Shallow and deep copy - 8 techniques for deep copying- 8 important points about cloning
Now let’s Deep clone arraylist in java.
I have seen many programmers getting confused in cloning stuff, so let's talk about this in detail when ArrayList has custom object and Double at times as well.
How to convert ArrayList to HashSet and Set to Array in Java examples
Program >
//ArrayList doesn't implements Cloneable,
import java.util.ArrayList;
import java.util.List;
class Item implements Cloneable{
Integer name;
Item(Integer name){
this.name=name;
}
public Item clone(){
return new Item(name);
//return new Item(new Integer(name));
}
}
public class Clone_ArrayList_blog {
public static void main(String[] args) {
List<Item> l = new ArrayList<>();
l.add(new Item(0));
l.add(new Item(1));
//Its just creating new ArrayList but all the elements on index 0 of l and l2 will point to same Item object
List<Item> l2=new ArrayList<>(l);
System.out.println(l==l2); //false
System.out.println(l.get(0)==l2.get(0)); //true (but for proper cloning it must be false, so do deep copy)
//Now do Deep copy
l2=new ArrayList<>();
for(Item d: l){
l2.add(d.clone());
}
System.out.println(l==l2); //false //OfCourse its ok and same as above
System.out.println(l.get(0)==l2.get(0)); //false (proper cloning )
System.out.println(l.get(0).name==l2.get(0).name); //true - For false do > return new Item(new Integer(name));
}
}
|
Interesting - Read how to Clone list of Double >
//Double doesn't implement Cloneable
public static void main(String[] args) {
List<Double> l = new ArrayList<>();
l.add(1d);
l.add(2d);
//Its just creating new ArrayList but all the elements on index 0 of l and l2 will point to same double object
List<Double> l2=new ArrayList<>(l);
System.out.println(l==l2); //false
System.out.println(l.get(0)==l2.get(0)); //true (but for proper cloning it must be false, so do deep copy)
//Now do Deep copy
l2=new ArrayList<>();
for(Double d: l){
l2.add(new Double(d));
}
System.out.println(l==l2); //false //OfCourse ike above
System.out.println(l.get(0)==l2.get(0)); //false (proper cloning , using new)
}
|
Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy(JMSE) on facebook, following on google+ or Twitter.
RELATED LINKS>