Skip to content

Java ArrayList clone example

Java ArrayList clone example shows how to clone ArrayList in Java. The example also shows how to deep clone ArrayList using the Cloneable interface and copy constructor.

How to clone ArrayList in Java?

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

This method returns a shallow copy of the ArrayList.

Output

Please note that, clone method makes a shallow copy of the ArrayList. That means, the 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 the ArrayList object was cloned, but its elements were not.

How to deep clone ArrayList and its contents?

As we have seen in the above example, cloning the ArrayList does not clone its elements. The 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, which means along with the ArrayList object itself, its elements should also be cloned.

Java provides the 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 the original ArrayList no more affects the cloned ArrayList. Instead of using the 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 a copy constructor

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

Output

This example is a part of the ArrayList in Java Tutorial.

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

About the author

Leave a Reply

Your email address will not be published.