This post will discuss how to construct a deep copy of a List in Java.

1. Using Object.clone() method

To facilitate field-for-field copy of instances of a class, make that class implement the Cloneable interface and override its Object.clone() method. Then you can iterate through the list, clone each item by invoking the clone() method, and add it to the cloned list.

The clone() method calls the clone() method of its parent class to obtain the copy, and copies all mutable fields to the instance. This is demonstrated below:

Download  Run Code

Output:

Student{name=’John’, dob=2017-12-13}
Student{name=’Akon’, dob=2017-12-13}
Student{name=’Tony’, dob=2017-12-11}

2. Implement clone() method

Another solution is to implement your own clone() method, instead of overriding the clone() method of the Object class. This can be effectively done using the Java 8 Stream, as shown below.

Download  Run Code

Output:

Student{name=’John’, dob=2017-12-13}
Student{name=’Akon’, dob=2017-12-13}
Student{name=’Tony’, dob=2017-12-11}

3. Copy Constructor

The copy constructor is the preferred way of copying objects in Java, instead of the clone() method. The copy constructor accepts just one argument that is another instance of the same class and creates a deep copy for all mutable fields.

Download  Run Code

Output:

Student{name=’John’, dob=2017-12-13}
Student{name=’Akon’, dob=2017-12-13}
Student{name=’Tony’, dob=2017-12-11}

That’s all about constructing a deep copy of a List in Java.