Arrays.copyOf() 与 System.arraycopy() 的区别
Arrays.copyOf()
源码
/**
@Description 复制指定的数组, 如有必要用 null 截取或填充,以使副本具有指定的长度
* 对于所有在原数组和副本中都有效的索引,这两个数组相同索引处将包含相同的值
* 对于在副本中有效而在原数组无效的所有索引,副本将填充 null,当且仅当指定长度大于原数组的长度时,这些索引存在返回的数组属于 newType 类
* @param <U> 源数组中元素的类型
* @param <T> 返回数组中元素的类型
* @param original 被复制的数组
* @param newLength 新数组的长度
* @param newType 返回数组的类型
* @return 原数组的“副本”,截取或用 null 填充以获得指定的长度
* @NegativeArraySizeException 如果参数newLength为负值
* @NullPointerException 如果参数original为null
* @ArrayStoreException 如果源数组中的元素不能被复制到类型为newType的数组中
*
* Arrays.copyOf()方法返回的数组是新的数组对象,拷贝不会影响原来的数组
*/
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;
}
测试
public static void main(String[] args) {
int[] original = {1,2,3,4,5};
int newLength = 8;
int[] dest = Arrays.copyOf(original, newLength);
for(int i=0; i<dest.length; i++) {
System.out.print(dest[i] + " ");
}
}
结果
System.arraycopy()
源码
/**
* @param src 原数组
* @param srcPos 原数组起始位置
* @param dest 目标数组
* @param destPos 目标数组起始位置
* @param length 需要被复制的元素个数
* @exception IndexOutOfBoundsException 索引溢出
* @exception ArrayStoreException 数据类型不匹配无法复制
* @exception NullPointerException 原数组和目标数组为空
*/
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
测试
public static void main(String[] args) {
int[] src = {1,2,3,4,5};
int srcPos = 0;
int[] dest = new int[5];
int destPos = 3;
int length = 2;
System.arraycopy(src, srcPos, dest, destPos, length);
for(int i=0; i<dest.length; i++) {
System.out.print(dest[i] + " ");
}
}
结果