System.arraycopy
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
src:原数组对象
srcPos:原数组起始位置
dest:目标数组对象
destPos:目标数组起始位置
length:复制长度
注意不要以为src和dest是Object类型,就可以随便传参,不是数组对象会报错。
该方法有一个一维数组、二维数组复制的区别,一维数组拷贝其值,二维数组拷贝引用,具体原理我将不清楚,有兴趣可以运行如下代码。
public class SystemArrayCopy {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = new int[3];
System.arraycopy(arr1, 0, arr2, 0, arr2.length);
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + " ");
}
System.out.println();
String[] sArr1 = {"China", "Japan", "Korea"};
String[] sArr2 = new String[3];
System.arraycopy(sArr1, 0, sArr2, 0, sArr2.length);
for (int i = 0; i < sArr2.length; i++) {
System.out.print(sArr2[i] + " ");
}
System.out.println();
sArr1[0] = "USA";
for (int i = 0; i < sArr2.length; i++) {
System.out.print(sArr2[i] + " ");
}
System.out.println();
String[][] ss1 = {{"sh", "js", "zj"}, {"bj", "tj", "hb"}, {"sc", "cq", "yn"}};
String[][] ss2 = new String[ss1.length][ss1[0].length];
System.arraycopy(ss1, 0, ss2, 0, ss1.length);
for (int i = 0; i < ss2.length; i++) {
for (int j = 0; j < ss2[i].length; j++)
System.out.print(ss2[i][j] + " ");
System.out.println();
}
System.out.println();
ss1[0][0] = "dsh";
for (int i = 0; i < ss2.length; i++) {
for (int j = 0; j < ss2[i].length; j++)
System.out.print(ss2[i][j] + " ");
System.out.println();
}
}
}
Arrays.copyOf
Arrays.copyOf()重载了很多类型,以int型为例
public static int[] copyOf(int[] original, int newLength);
original:原数组
newLength:复制长度
返回新复制的数组对象
分析Arrays的源代码可知底层实际上是调用System.arraycopy()
Object.clone
在Java中,数组也是一种对象,所以可以使用clone()方法。
String[] sArr1 = {"China", "Japan", "Korea"};
String[] sArr2;
sArr2 = sArr1.clone();
for (int i = 0; i < sArr2.length; i++) {
System.out.print(sArr2[i] + " ");
}