Arrays.copyOf和System.arraycopy之间的区别
2016-08-03 20:29
549 查看
看vector中的源码,发现了有些部分使用的是System.arraycopy,另外一部分使用的Arrays.copyOf,就看了下,发现如果已经明确指定了目标数组和源数组的就是直接用的System的那个方法,如果没有明确指定,则是使用的后者,研究一下源码发现如下关系
首先是System.arraycopy的源码
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);看到方法上使用native修饰的,说明方法的实现是底层用c++写的,包含四个参数
源数组,源数组开始的位置,目标数组,目标数组开始的位置,最后一个参数是要复制数组元素的数量
然后再看看Arrays.copyOf的源代码
* @since 1.6 */ public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { @SuppressWarnings("unchecked") T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }以及它的重载 方法
* @since 1.6 */ @SuppressWarnings("unchecked") public static <T> T[] copyOf(T[] original, int newLength) { return (T[]) copyOf(original, newLength, original.getClass()); }这里只是列举了使用泛型的两个重载方法,并且注释中指明是从jdk1.6开始拥有的
第一个参数表示源数组,第二个表示复制的长度,最后一个参数是指定类型
从第个方法的实现中看到首先新建了一个数组作为目标数组,然后调用System.arraycopy方法,最后将数组返回
通过分析两个方法的源代码,发现Array.copyOf是基于前一个方法的实现,适合目标数组不明确的情况,在目标数组已经指明的情况下直接调用系统的那个复制方法
相关文章推荐
- System.arraycopy(src, srcPos, dest, destPos, length) 与 Arrays.copyOf(original, newLength)区别
- Arrays.copyof(···)与System.arraycopy(···)区别
- Java-Java中System.arraycopy() 和 Arrays.copyOf()两者之间的区别
- Arrays.copyof(···)与System.arraycopy(···)区别
- 在Java中System.arraycopy() 和 Arrays.copyOf()两者之间的区别
- java中System.copyArray与Arrays.copyof区别
- System.arraycopy() 与 Arrays.copyOf()两个方法的区别
- Arrays.copyof(···)与System.arraycopy(···)数组元素复制区别
- 在Java中System.arraycopy() 和 Arrays.copyOf()两者之间的区别?
- Arrays.copyof(···)与System.arraycopy(···)区别
- Arrays.copyOf()与System.arraycopy()的源码分析
- System.arraycopy() vs. Arrays.copyOf() in Java
- JAVA System.arraycopy 和Arrays.copyof 效率比较
- System.arraycopy()和Arrays.copyOf()的区别
- Arrays.copyof()和System.arraycopy()方法总结
- Arrays.copyOf(...)和System.arraycopy(...)
- Arrays.copyof(···)与System.arraycopy(···)区别
- System.arraycopy 和 Arrays.copyOf()的区别
- [java]Arrays.copyOf() VS System.arrayCopy()
- Java编程:Arrays.copyOf()与System.arraycopy()的分析