ArrayList的源码中数组的拷贝用到该方法:
public static void arraycopy(Object src, --源数组
int srcPos, --源数组要复制的起始位置
Object dest, --目的数组;
int destPos, --目的数组放置的起始位置;
int length) --length:复制的长度(源数组)。
对于基本类型来说:
int[] is = {1,2,3,4,5};
int[] is2 = {4,0,9};
System.arraycopy(is, 2, is2, 1, 2);
is[2] = 99;
System.out.println("is=" + Arrays.toString(is));
System.out.println("is2=" + Arrays.toString(is2));
运行结果:
is=[1, 2, 99, 4, 5]
is2=[4, 3, 4]
对于引用类型来Person:
class Person { String name; Person(String n) { this.name = n; }
public String toString() { return "Person [name=" + name + "]"; }
}
引用类型测试:
Person[] p1 = {new Person("A"),new Person("B"),new Person("C")}; Person[] p2 = new Person[4]; p2[0] = new Person("kaixin"); System.arraycopy(p1, 0, p2, 1, p1.length); System.out.println("改变前p1=" + Arrays.toString(p1)); System.out.println("改变前p2=" + Arrays.toString(p2)); p1[1].name = "CCCCC"; System.out.println("改变后p1=" + Arrays.toString(p1)); System.out.println("改变后p2=" + Arrays.toString(p2));
引用类型测试结果:
改变前p1=[Person [name=A], Person [name=B], Person [name=C]] 改变前p2=[Person [name=kaixin], Person [name=A], Person [name=B], Person [name=C]] 改变后p1=[Person [name=A], Person [name=CCCCC], Person [name=C]] 改变后p2=[Person [name=kaixin], Person [name=A], Person [name=CCCCC], Person [name=C]]