Collections

Java ArrayList clone example

Java ArrayList clone example shows how to clone ArrayList in Java. Example also shows how to deep copy ArrayList (clone ArrayList and its contents) using Cloneable and copy constructor in Java.

How to clone ArrayList in Java?

Cloning an object comes very handy in certain situations where you need to make a copy of ArrayList before making any changes to the original ArrayList. You can clone ArrayList using its clone method.

This method returns shallow copy of the ArrayList.

Output

Please note that, clone method makes a shallow copy of the ArrayList. That means, ArrayList object is cloned, but its content is not. ArrayList elements still refer to the same objects. To understand it more clearly, see below given example.

Output

As you can see from the output, when we changed the StringBuilder object, it also affected the contents of the cloned ArrayList. That is because only ArrayList object was cloned, but its elements were not.

How to deep clone ArrayList and its contents?

As we have seen in above example, cloning the ArrayList does not clone its elements. Elements still refer to the original objects in the Heap. Changing the element in one List also affects another. To overcome this problem, the ArrayList needs to be deep cloned, that means along with the ArrayList object itself, its elements should also be cloned.

Java provides Cloneable interface (a marker interface with no methods) to mark that the class implementing it supports cloning.

ArrayList deep cloning example

Output

As you can see from the output, changing the element in original ArrayList no more affects the cloned ArrayList. Instead of using clone method of ArrayList, we iterated through the ArrayList elements, and cloned them before adding them to the copied ArrayList. In the Students class, we implemented the Cloneable interface and overridden the clone method of Object class.

Deep cloning ArrayList using copy constructor

Instead of implementing Cloneable interface and overriding the clone method, we can also write copy constructor in the Student class. Copy constructor is a constructor which accepts the object of the same class as a parameter and copies all the properties of it as given below.

Output

Please let us know your views in the comments section below.

Join 1000+ fellow learners! Enter your email address below: