In Java, List is an interface, and the common implementation classes are ArrayList and LinkedList. When we need to copy a List, there are usually two methods: shallow copy and deep copy. A shallow copy only copies the references in the List, while a deep copy copies all the elements in the List. Let's take a look at how to implement a deep copy of List.
Suppose we have a Person class with two properties named and age:
csharp
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Now we have a List that contains some Person objects:
java
import java.util.ArrayList;
import java.util.List;
public class DeepCopyExample {
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
list.add(new Person("Tom", 18));
list.add(new Person("Jerry", 20));
list.add(new Person("Mike", 22));
System.out.println("Original list: " + list);
}
}
To implement a deep copy of List, you can use the constructor of java.util.ArrayList:
java
import java.util.ArrayList;
import java.util.List;
public class DeepCopyExample {
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
list.add(new Person("Tom", 18));
list.add(new Person("Jerry", 20));
list.add(new Person("Mike", 22));
System.out.println("Original list: " + list);
// 深拷贝
List<Person> copy = new ArrayList<>(list);
System.out.println("Copy list: " + copy);
}
}
In the above code, we use the constructor of ArrayList to create a new List and pass the original list as a parameter. The new list thus created is a deep copy of the original list.