Arrays.copyOf
public static int[] copyOf(int[] original, int newLength) {
int[] copy = new int[newLength];
System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
return copy;
}
方法其实就是返回一个数组,而这个数组就等于数组array的前 newLength 数。
其实内部用了 System.arraycopy 方法
举例:
int[] array = new int[]{1, 2, 3, 4, 5};
int[] array2 = Arrays.copyOf(array, 3);
//array2结果:[1,2,3]
Arrays.copyOfRange
public static int[] copyOfRange(int[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
int[] copy = new int[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
复制原数组的一段值,长度是 to - from
举例:
int[] array = new int[]{1, 2, 3, 4, 5};
int[] array2 = Arrays.copyOfRange(array, 1,3);
//array2 结果:[2,3]
System.arraycopy
这是一个 native 方法
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
参数解释:
- src 源数据
- srcPos 源数据起始位置
- dest 目标数据
- destPos 目标数据其实位置
- length 复制的长度
举例:
String[] array = new String[]{"1", "2", "3", "4", "5"};
String[] array2 = new String[5];
array2[0] = "a";
array2[1] = "b";
array2[2] = "c";
System.arraycopy(array, 1, array2, 2, 2);
//array2 结果:["a", "b", "2", "3", null]