title: System.arraycopy和Arrays.copyof的区别
date: 2021-05-31 21:22:04
tag:
突然用到这两个,感觉很好奇,对比一下
首先看源码
这是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;
}
可见Arrays.copyof创建了一个新的数组copy
然后调用System.arraycopy方法进行copy,后面**Math.min(original.length, newLength)**显示了可以copy数组的部分形成一个拷贝,返回的是新的数组copy。
而对于System.arraycopy
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
src是源数组
srcpos是源数组的起始位置
dest是目的数组
destPos是目的数组的起始位置
length - 要复制的数组元素的数量
该方法是用了native关键字,调用的为C++编写的底层函数,可见其为JDK中的底层函数。
再来看看Arrays.copyOf();该方法对于不同的数据类型都有相应的方法重载。