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]