其中 Arrays.copy是JDK1.6中引用的新方法。它调用了System.arraycopy完成相关数组的复制。
在JDK1.6中ArrayList的相关add remove等操作都是调用System.arraycopy来对其底层的Object[]elementData数组进行操作的。
LinkedList则使用一个Entry的内部类,其有指向next和previous的引用保存元素,它的遍历则先计算出所需index和size>>1(以为后的大小),确定是通过previous还是next遍历。
System.arraycopy
01.public static void arraycopy(Object src, 02. int srcPos, 03. Object dest, 04. int destPos, 05. int length) 06. 从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。从 src 引用的源数组到 dest 引用的目标数组,数组组件的一个子序列被复制下来。被复制的组件的编号等于 length 参数。源数组中位置在 srcPos 到 srcPos+length-1 之间的组件被分别复制到目标数组中的 destPos 到 destPos+length-1 位置。 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/yangqillohe/archive/2010/05/26/5625159.aspx
它是个native方法,测试结果表明,
当数组很小,但存是调用次数多的话。
使用它复制数组并不比for循环手工复制数组快。
int count = 10000000; long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { System.arraycopy(intArray1, 0, intArray2, 0, intArray1.length); } long end = System.currentTimeMillis() - start; System.out.println("use " + end); long start2 = System.currentTimeMillis(); for (int i = 0; i < count; i++) { for (int j = 0; j < intArray1.length; j++) { intArray2[j] = intArray1[j]; } } long end2 = System.currentTimeMillis() - start2; System.out.println("use " + end2); int count = 10000000; long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { System.arraycopy(intArray1, 0, intArray2, 0, intArray1.length); } long end = System.currentTimeMillis() - start; System.out.println("use " + end); long start2 = System.currentTimeMillis(); for (int i = 0; i < count; i++) { for (int j = 0; j < intArray1.length; j++) { intArray2[j] = intArray1[j]; } } long end2 = System.currentTimeMillis() - start2; System.out.println("use " + end2); use 224 use 105
但是如果是数组比较大,那么使用System.arraycopy会比较有优势,因为其使用的是内存复制,省去了大量的数组寻址访问等时间。