前面的博客已经提到了一维数组和二维数组的拷贝的判断。
Java中常用的是对对象的拷贝。
对象的拷贝:
1、可以直接
2、clone()
Peolple类:
package Lianxi;
public class Peolple implements Cloneable{
private String name;
private int age;
private int height;
public Student student;
public Peolple(String name,int age){
this.name=name;
this.age=age;
student=new Student();
}
public void eat(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void drink(){
}
@Override
protected Object clone() throws CloneNotSupportedException {
Peolple p=(Peolple)super.clone(); //只能对基本数据类型和String类型进行深拷贝
//引用数据类型不行
p.student=(Student)student.clone(); //调用Student中重写的对Student中的内容进行拷贝
return p;
}
}
Student类:
package Lianxi;
public class Student implements Cloneable{
public int age=1;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Test
package Lianxi;
import zuoye4.People;
public class Test {
public static void main(String []args){
Peolple p1=new Peolple("wo",10);
Peolple p2=null;
try{
p2=(Peolple)p1.clone();
}
catch(Exception e){
}
System.out.println(p1.getAge()+p1.getName()+p1.student.age);
System.out.println(p2.getAge()+p2.getName()+p2.student.age);
p1.student.age=50;
System.out.println(p1.student.age);
System.out.println(p2.student.age);
}
}
输出结果:
10wo1
10wo1
50
1
该过程用clone()实现深拷贝。
注意:对引用数据的深拷贝,要重写clone()方法。