美文网首页
Java 对象克隆

Java 对象克隆

作者: VickyShen | 来源:发表于2019-03-12 10:55 被阅读0次

    Java的拷贝可以分为浅拷贝和深拷贝。

    浅拷贝

    浅拷贝示意图

    原变量和拷贝变量引用同一个对象,改变一个变量锁引用的对象将会对另一个变量产生影响。

            Person original = new Person("johb",20);
            Person copy = origin;
            copy.setAge(21); 
    

    result: original only changed!!!

    深拷贝(也叫做克隆)

    深拷贝示意图
    如果想创建一个对象的copy,它的初始状态和original一样,但是以后可以改变各自的状态,那就需要使用clone方法
    clone是Object的protected方法,Object中的clone方法,由于object类对具体的类对象一无所知,所以只能讲各个域进行对应的拷贝。如果对象中的数据域都是数值或者基本数据类型,这样的拷贝没有问题,如果对象中包含了子对象,那么拷贝的结果会使得两个域引用同一个子对象。默认的克隆操作是浅拷贝,沒有克隆包含在对象中的内部对象。
    而且,由于clone方法是保护方法,所以用户不能直接调用它,需要在类中重新定义clone方法。
    public class Person implements Cloneable{
        public Employee clone() throws CloneNotSupportedException {
            return (Employee )super.clone();
        }
    }
    

    上述clone方法没有在Object.clone()提供的浅拷贝的基础上新增任何东西,而只是将这个方法声明为public。为了实现深拷贝,必须克隆所有可变的实例域

    public class Person implements Cloneable{
        public Employee clone() throws CloneNotSupportedException {
            Employee cloned = (Employee )super.clone();
            cloned.hireDay = (Data)hireDay.clone;
            return cloned;
        }
    }
    

    当子对象可变,必须重新定义克隆方法,以便实现克隆子对象的深拷贝

    数组链表的拷贝

    数组链表也是一种对象,若元素不是基本数据类型时,相当于内部对象,因此以下几种方式都是浅拷贝。原始链表和拷贝链表共享元素。

    几种浅拷贝

    遍历循环复制

            List<Person> srcList = new ArrayList<>();
            srcList.add(new Person("jack", 24));
            srcList.add(new Person("rose", 22));
            List<Person> destList = new ArrayList<>(srcList.size());
            for (Person p : srcList) {
                destList.add(p);
            }
    

    使用List实现类的构造方法

            List<Person> srcList = new ArrayList<>();
            srcList.add(new Person("jack", 24));
            srcList.add(new Person("rose", 22));
            List<Person> destList1 = new ArrayList<Person>(srcList);
    

    list.addAll方法

            List<Person> srcList = new ArrayList<>();
            srcList.add(new Person("jack", 24));
            srcList.add(new Person("rose", 22));
            List<Person> destList2 = new ArrayList<Person>();
            destList2.addAll(srcList);
          
    

    System.arraycopy方法

            List<Person> srcList = new ArrayList<>();
            srcList.add(new Person("jack", 24));
            srcList.add(new Person("rose", 22));
            List<Person> destList = new ArrayList<>(srcList.size());
            Person[] srcPersons = srcList.toArray(new Person[0]);
            Person[] destPersons = new Person[srcPersons.length];
            System.arraycopy(srcPersons, 0, destPersons, 0, srcPersons.length);
    

    其实跟进去java代码,发现上述三种本质都是调用了System.arraycopy方法
    上述拷贝方法,改变了A的元素的属性,会改变B。

            srcList.get(0).setName("change!!");
    
    image.png

    不过,直接对A进行新增元素等操作,并不会影响B。

            srcList.add(new Person("gga",23));
    

    数组链表的深拷贝

    序列化

    public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {  
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();  
        ObjectOutputStream out = new ObjectOutputStream(byteOut);  
        out.writeObject(src);  
     
        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());  
        ObjectInputStream in = new ObjectInputStream(byteIn);  
        @SuppressWarnings("unchecked")  
        List<T> dest = (List<T>) in.readObject();  
        return dest;  
    }  
     
    List<Person> destList=deepCopy(srcList);  //调用该方法
    

    clone方法

    public class A implements Cloneable {   
        public String name[];   
     
        public A(){   
            name=new String[2];   
        }   
     
        public Object clone() {   
            A o = null;   
            try {   
                o = (A) super.clone();   
            } catch (CloneNotSupportedException e) {   
                e.printStackTrace();   
            }   
            return o;   
        }   
    }  
    for(int i=0;i<n;i+=){
    copy.add((A)src.get(i).clone());
    }
    
    

    参考
    java List复制:浅拷贝与深拷贝
    java核心技术卷1 P76 P213

    相关文章

      网友评论

          本文标题:Java 对象克隆

          本文链接:https://www.haomeiwen.com/subject/fboipqtx.html