1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.ArrayList;

public class Person implements Cloneable {

private String name;
private ArrayList<Integer> books;

public Person(String name, ArrayList<Integer> books) {
this.name = name;
this.books = books;
}

public ArrayList<Integer> getBooks() {
return books;
}

public void setBooks(ArrayList<Integer> books) {
this.books = books;
}

@Override
protected Object clone() throws CloneNotSupportedException {
Object obj = super.clone();
((Person) obj).setBooks((ArrayList<Integer>) books.clone());
return obj;
}

public static void main(String[] args) {
try {
ArrayList<Integer> books = new ArrayList<>();
books.add(1);
books.add(2);
Person p1 = new Person("张三", books);
Person p2 = (Person) p1.clone();
p2.setBooks(null);
System.out.println("p1=" + p1.getBooks());
System.out.println("p2=" + p2.getBooks());
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}

}
1
2
p1=[1, 2]
p2=null