System.arraycopy 是浅拷贝? - 点滴记忆*记忆点滴
收藏本站

System.arraycopy 是浅拷贝?

    jdk 5新增的java.util.concurrent 包中有个CopyOnWriteArrayList类。从名字及所属包猜得出他是个与线程安全有关的List实现类。但今天我主要关心的还不是它,而是发现源代码中在这个类中元素集合改变时除了同步以外还大量用到 System.arraycopy 进行元素拷贝。于是引发了System.arraycopy 是深拷贝还是浅拷贝这个问题。这个方法是native 方法,传说速度是比较快的。但也就没法让我通过读源代码确定其是深拷贝还是浅拷贝。不过有copy 两字,我想应该是深拷贝,不然也就没必要建这个方法,况且还是本地方法。但工科是不能用猜的,还是做实验吧。


    public static void main(String[] args) {  

    	StringBuilder[] a =  new StringBuilder[3];
    	a[0] = new StringBuilder("aaa");
    	a[1] = new StringBuilder("bbb");
    	a[2] = new StringBuilder("ccc");
    	StringBuilder[] b = Arrays.copyOf(a,2);
    	
    	System.out.println(a[1]);
    	System.out.println(b.length);
    	System.out.println(a == b);
    	
    	b[1].append("ddd");
    	System.out.println(a[1]);
    	System.out.println(b[1]);
    }
运行一下,结论很明显。


是深拷贝,因为 a ==  b  输出为false了。

但是,b[1]修改以后,a[1]也修改了,说明他们是同一个引用,又是浅拷贝了。

所以结论就是,是深拷贝,但不是完全的深拷贝。这也很容易理解。没必要,也做不到。它就是相当于以下代码


    public static void main(String[] args) {  
    	StringBuilder[] a =  new StringBuilder[3];
    	a[0] = new StringBuilder("aaa");
    	a[1] = new StringBuilder("bbb");
    	a[2] = new StringBuilder("ccc");
    	StringBuilder[] b = new StringBuilder(2);
    	b[0]=a[0];
        b[1]=a[1];

    	System.out.println(a[1]);
    	System.out.println(b.length);
    	System.out.println(a == b);
    	
    	b[1].append("ddd");
    	System.out.println(a[1]);
    	System.out.println(b[1]);
    }




    留下足迹