Java中的clone简单探索总结,深拷贝与浅拷贝

    技术2024-08-02  71

    package test; import java.util.Iterator; import java.util.Vector; class AA implements Cloneable{//如果不实现这个接口,即使覆盖了clone,编译无措,运行抛异常 int a; BB d = new BB(2021); AA(int a){ this.a = a; } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub AA temp = (AA)super.clone();//对于基本数据类型还能深拷贝,但对象指针不行 temp.d = (BB)this.d.clone(); //如果不显式地调用对象成员地clone,则为浅拷贝 return temp; } } class BB implements Cloneable{ //你如果没有覆盖clone,那么当你作为成员时,只能是浅拷贝 int a; BB(int a){ this.a = a; } protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return super.clone(); } } public class Vector_test { public static void main(String[] args) { // TODO Auto-generated method stub Vector<Integer> vec = new Vector<Integer>();//Java中的大部分类自带clone,String等除外 vec.add(202); vec.add(10); Vector<Integer> vec1 = (Vector<Integer>)vec.clone(); vec1.set(0, 9); for(int v : vec1) System.out.println(v); AA prio = new AA(2020); System.out.println(prio.d);//#### try { AA save = (AA)prio.clone(); System.out.println(save.d);//####两者地址不一样,说明发生了深拷贝 } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block System.out.println("Exception!"); e.printStackTrace(); } } }
    Processed: 0.013, SQL: 9