如果想要拷贝一个数组,可能会使用 System.arraycopy() 或者 Arrays.copyOf() 两种方式。
1、System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
- src:源数组
- srcPos:源数组复制的起点
- destPos:目标数组
- destPos:目标数组写入的起点
- length:复制的长度
2、Arrays.copyOf(T[] original, int newLength)
- origin:源数组
- newLength:新数组的长度
区别:
- Arrays.copyOf():不仅仅只是拷贝数组中的元素,在拷贝元素时,会创建一个新的数组对象
- System.arraycopy():在给定数组间进行拷贝
Arrays.copy() 底层实现:
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;}
