数组复制的5种方法源码分析
文章目录
1.For循环方法
一个一个复制,代码效率低。
2.System.arraycopy()方法
方法使用native关键字修饰,为原生方法,效率高。源码如下:
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
参数说明
src 源数组
srcPos 源数组的开始位置
dest 目的数组
destPos 目的数组的开始位置
length 复制的长度
3.Arrays.copyOf()方法
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;
参数说明
original 源数组
newLength 复制长度(复制从源数组第一位开始),也是新数组长度,
返回值
返回新数组,数组的大小就看源数组与复制长度谁大了。
可一个看出Arrays.copyOf()其实也是调用原生方法System.arraycopy(),所以效率必然是比原生方法慢。
4.Arrays.CopyOfRange()
Arrays.CopyOfRange() 也是调用原生方法System.arraycopy(),只是参数与Arrays.copyOf()不同。有范围的复制更加灵活。
public static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
参数说明
original 源数组
from 复制开始的位置
to 复制结束点
newType 数组类型
5.Object.clone()方法
数组复制同样也是原生方法,源码如下
protected native Object clone() throws CloneNotSupportedException;
返回值
返回Object,所以需要用强转,效率只比for循环快。
6.总结
效率对比排名
-
System.arraycopy() 只用使用参数数组,不需要新建数组实现,无返回值
-
Arrays.copyOf()与 Arrays.CopyOfRange() 需要新建数组,返回新数组
-
Object.clone() 返回Object,所以需要用强转,所以比较慢
-
for循环