How to Deep Copy Arraylist in Java

In this article, we are going to learn deep copy ArrayList in Java.

There are mainly two concepts Shallow copy and deep copy.

When an object gets copied via reference not actual values then it is called Shallow copy. In it, changes made to an object will also reflect to another object. It means if we change elements of one object then the other object will also be changed.

In deep copy, the copied object is completely independent and changes made to it do not reflect to the original object.
Let’s understand with the examples.

Example of Deep Copy ArrayList

Here, we are copying one ArrayList elements to ther using addAll() method and see changes made to second list does not modify original list.

Output:

[India, US, China] [India, US, China] [India, Russia, China]

Note: This method will only work if ArrayList contains primitive data types or immutable collection. In case, ArrayList contains custom objects, then we need to explicitly clone the custom objects.

Deep Copy using Clone() Method

We can also use clone() method to create a copy of ArrayList but this method create swallow copy.

Let’s see with the help of example.

Create main class named CloneArrayListMain.java

Output

———–Original List———–
John 102
David 105
———–Copied List———-
John 102
David 105

As you can see, changes to clonedStudentList also got reflected in studentList.

To create a true deep copy of ArrayList, we should create a new ArrayList and copy all the cloned elements to new ArrayList one by one and we should also clone Student object properly.

To create deep copy of Student class, we can divide its class members to mutable and immutable types.

  • Immutable fields( String data types): We can directly use immutable fields in cloned object. Immutable fields include wrapper classes, String and primitive types.
  • Mutable fields(Date data type): We should create new object for the mutable attribute and then assign it to cloned object.

Here is the correct clone method for Student class.

As you can see, we have used super.clone() to clone the Student object and then set dateOfBirth explicitly to clonedStudent as Date is mutable field.

Here is code to create deep copy of ArrayList by copying cloned elements one by one to new ArrayList.

Complete code to deep copy ArrayList in java

Here is complete java program to create deep copy of ArrayList in java.

As you can see, changes made to clonedStudentList did not reflect in original ArrayList studentList.

That’s all about how to deep copy ArrayList in java.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 20 September

    Return ArrayList in Java

    Table of ContentsReturn ArrayList in Java From a Static MethodReturn ArrayList in Java From a Non-static MethodConclusion This article discusses cases of returning an ArrayList in Java from a method. An ArrayList in Java is a collection of elements of the same data type under a single variable name. In different cases, you can return […]

  • 17 September

    Create List with One Element in Java

    Table of ContentsUsing Collections.singletonList()Using Array.asList() method [ Immuatable list]Using new ArrayList with Array.asList() method [ Mutable list] In this post, we will see how to create List with One Element in java.. Using Collections.singletonList() This is best way to create List with single element if you need an immutable List. [crayon-632f5ac7c2948334510860/] Output [crayon-632f5ac7c2954287023258/] If you […]

  • 17 May

    How to Add Multiple Values for Single Key In HashMap in Java

    Table of ContentsHashMapCan HashMap Store Multiple Values AutomaticallyWays to Add Multiple Values for Single Key In HashMap in JavaUsing the Standard LibraryUsing Apache Commons LibraryUsing Google Guava LibraryUsing TreeSet as ValuesUsing a Wrapper ClassUsing Java TuplesUsing compute() Function in JDK 8Conclusion This article discusses the HashMap in Java and how to add multiple values for […]

  • java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
    22 February

    [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

    Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]

  • Java ArrayList of objects
    25 January

    Create ArrayList of Objects in Java

    Table of ContentsUsing the add() method to create ArrayList of objects in javaUsing parameterized constructor to create ArrayList of objects in javaUsing addAll() method to create ArrayList of objects in javaConclusion In this tutorial, we will learn how to create ArrayList of objects in Java. We will create a Book class with different properties and […]

  • 10 September

    How to remove element from Arraylist in java while iterating

    Table of ContentsIntroductionUsing Collection’s removeIf() methodUsing ListIterator classUsing removeAll() methodUsing Java 8 Stream to filter List itemsConclusion Introduction In this tutorial, you will learn how to remove element from Arraylist in java while iterating using different implementations provided by Java. It is necessary to understand the right way to remove items from a List because […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.