Arrays.copyof

 public static int[] copyOf(int[] original, int newLength) {

        int[] copy = new int[newLength];

        System.arraycopy(original, 0, copy, 0,

                         Math.min(original.length, newLength));

        return copy;

    }

首先new一个新数组 然后copy过去 return这个新数组

int[] strArray = new int[] {1,2,3,4};

int[] copyArray=Arrays.copyOf(strArray,2);

结果copyArray就是1,2

int[] strArray = new int[] {1,2,3,4};

int[] copyArray=Arrays.copyOf(strArray,10);

结果1 2 3 4 0 0 0 0 0 0 

不会报错 因为最后的数组总是按后面那个newLength规定的新数组来说 

 

 

用System.arraycopy:

int[] strArray = new int[] {1,2,3,4};

        int[] copyArray = new int[4];

        System.arraycopy(strArray, 0, copyArray, 0, 5);

直接报错:java.lang.ArrayIndexOutOfBoundsException

如果把最后的5改成3

copyArray :1 2 3 0 

 

 

 

定义一个数组int[] a={3,1,4,2,5}; int[] b=a;  数组b只是对数组a的又一个引用,即浅拷贝。如果改变数组b中元素的值,其实是改变了数组a的元素的值

要实现深度复制,可以用clone或者System.arrayCopy
如下面的代码

1 int[] a={3,1,4,2,5};
2 int[] b=a.clone();
3 b[0]=10;
4 System.out.println(b[0]+"  "+a[0]);

 输出为10  3
可见改变了b的值,但是没有改变a的元素的值

但是clone和System.arrayCopy都是对一维数组的深度复制。对于二维数组

1 int[][] a={{3,1,4,2,5},{4,2}};
2 int[][] b=a.clone();
3 b[0][0]=10;
4 System.out.println(b[0][0]+"  "+a[0][0]);

输出为10  10
所以clone并不能直接作用于二维数组
因为java中没有二维数组的概念,只有数组的数组。所以二维数组a中存储的实际上是两个一维数组的引用。当调用clone函数时,是对这两个引用进行了复制。
要证明,只需看下面的输出

1 int[][] a={{3,1,4,2,5},{4,2}};
2 int[][] b=a.clone();
3 b[0][0]=10;
4 System.out.println(b[0][0]+"  "+a[0][0]);
5 System.out.println(a[0]==b[0]);

第5句输出为true。

用clone对二维数组进行复制,要在每一维上调用clone函数

1 int[][] a={{3,1,4,2,5},{4,2}};
2 int[][] b=new int[a.length][];
3 for(int i=0;i<a.length;i++){
        b[i]=a[i].clone();
}
 b[0][0]=10;
6 System.out.println(b[0][0]+"  "+a[0][0]);
7 System.out.println(b[0]==a[0]);

输出为
10  3
false

你可能感兴趣的:(Arrays)