Java深度克隆
java克隆需要首先实现Cloneable接口,浅克隆只是会克隆一些基本的数据类型,对于复杂的数据类型,比如List,Map,需要重写克隆方法,不然克隆出来的对象属于同一个对象,造成混乱。
/**
* class Student
*/
package com.whpu.deep;
import java.util.ArrayList;
import java.util.List;
public class Student implements Cloneable{
private String name;
private int age;
private String gender;
private List<String> friends;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public List<String> getFriends() {
return friends;
}
public void setFriends(List<String> friends) {
this.friends = friends;
}
public Student clone(){
try {
Student student = (Student)super.clone();
List<String> new_friends=new ArrayList<String>();
for(String friend:this.getFriends()){
new_friends.add(friend);
}
student.setFriends(new_friends);
return student;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
}
/**
* class Client
*/
package com.whpu.deep;
import java.util.List;
import java.util.ArrayList;
public class Client {
public static void main(String[] args) {
Student s1=new Student();
/*
Student s2=s1;
b System.out.println(s1==s2);
*/
List<String> friends=new ArrayList<String>();
friends.add("Swift");
friends.add("Peter");
s1.setFriends(friends);
Student s2=s1.clone();
System.out.println(s1.getFriends());
System.out.println(s2.getFriends());
friends.add("Joe");
s1.setFriends(friends);
System.out.println(s1.getFriends());
System.out.println(s2.getFriends());
}
}