ArrayList<Integer> a=new ArrayList<Integer>(); a.add(5); ArrayList<Integer> b=(ArrayList<Integer>)a.clone(); a.add(6); System.out.println(b.toString());
In the above piece of code, i think clone()
does a shallow copy. So, b
and a
should point to the same memory location. However, when i do b.toString()
, the answer is only 5
. Why is 6
also not displayed if clone()
does a shallow copy?
ArrayList clone() method is used to create a shallow copy of the list.
Default version of clone method creates the shallow copy of an object. To create the deep copy of an object, you have to override clone method. Shallow copy is preferred if an object has only primitive fields. Deep copy is preferred if an object has references to other objects as fields.
A “shallow copy” in Java is often referred to a copy of the pointer value of a object instead of the actual contents the object is containing. In the case of an ArrayList<Elements> old, a shallow copy is another ArrayList<Elements> copy but the pointers in the ArrayList points to the same elements.
ArrayList cloned = new ArrayList(collection c); where c is the collection containing elements to be added to this list. Approach: Create a list to be cloned. Clone the list by passing the original list as the parameter of the copy constructor of ArrayList.
Shallow copy does not mean that they point to the same memory location. That would be just an assignment:List b = a;
.
Cloning creates a new instance, holding the same elements. This means you have 2 different lists, but their contents are the same. If you change the state of an object inside the first list, it will change in the second list. (Since you are using an immutable type - Integer
- you can't observe this)
However, you should consider not using clone()
. It works fine with collections, but generally it's considered broken. Use the copy-constructors - new ArrayList(originalList)
If it was like you thought, then the clone
method would be completely useless, because in that case, the following lines would be equivalent:
ArrayList<Integer> b = (ArrayList<Integer>)a.clone(); ArrayList<Integer> b = a;
Cloning is - like in real world scenarios - a process of creating two entities with exactly the same properties (at the time of the cloning operation).
And as Bozho mentioned - avoid the Java clone()
concept. Even it's author mentioned, that it is broken.
This question and it's answers are quite valuable and provide a link to Josh Blochs own comments on his piece of work ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With