JAVA中的浅拷贝与深拷贝

时间:2022-11-08 19:54:34

JAVA中的浅拷贝与深拷贝

 

浅拷贝:实现Clonenable接口并覆盖clone()方法

 1  @Override  2       public Object clone() {  3             Student stu = null;  4             try{  5                stu = (Student)super.clone();  6             }catch(CloneNotSupportedException e) {  7  e.printStackTrace();  8  }  9             return stu; 10       } 

 

深拷贝:

 1  @Override  2       public Object clone() {  3             Student stu = null;  4             try{  5                 stu = (Student)super.clone();  6             }catch(CloneNotSupportedException e) {  7  e.printStackTrace();  8  }  9         stu.addr = (Address)addr.clone();    //深度复制
10             return stu; 11       }