1.arraycopy
int [] oldArray = {1,2,3,4,5};
int [] dest =new int[5];
System.arraycopy(oldArray,2,dest,0,3);
输出: 3 4 5 0 0
int [] dest =new int[5];
System.arraycopy(oldArray,2,dest,1,3);
输出:0 3 4 5 0
//如果目标数组长度太小等会 导致引发越界异常
//下述的代码均会引发ArrayIndexOutOfBoundsException异常
int [] dest =new int[2];
System.arraycopy(oldArray,2,dest,1,3);
int [] dest =new int[5];
System.arraycopy(oldArray,3,dest,1,3);
2.Arrays.copyOf(int[] original, int newLength)
此方法返回一个新的数组,内部还是调用了arraycopy方法,
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;
}
int [] oldArray = {1,2,3,4,5};
int[] newArray = Arrays.copyOf(oldArray, 3);
输出: 1 2 3
int [] oldArray = {1,2,3,4,5};
int[] newArray = Arrays.copyOf(oldArray, 4);
输出: 1 2 3 4
int [] oldArray = {1,2,3,4,5};
int[] newArray = Arrays.copyOf(oldArray, 5);
输出:1 2 3 4 5