遍历复制
通过遍历数组,遍历的过程中把原数组中的数据复制到新的数组中
System.arraycopy
源码:
* @param src the source array. //原数组
* @param srcPos starting position in the source array. //在原数组中开始复制的位置
* @param dest the destination array. //目标数组
* @param destPos starting position in the destination data.//目标数组中开始的位置
* @param length the number of array elements to be copied.//要复制的数组元素的数量
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
实例
int[] arr = {1,2,3,4,5,6,7};
int[] arr1 = new int[7];
System.out.println(Arrays.toString(arr1));
System.arraycopy(arr,0,arr1,0,7);
System.out.println(Arrays.toString(arr1));
输出:
[0, 0, 0, 0, 0, 0, 0]
[1, 2, 3, 4, 5, 6, 7]
Arrays.copyOf
源码:
需要注意的是该方法是一个重载的方法,第一个参数为要复制的数组,第二个参数系数组的长度
public static int[] copyOf(int[] original, int newLength)
案例
int[] arr = {1,2,3,4,5,6,7};
int[] arr2 = Arrays.copyOf(arr,arr.length);
System.out.println(Arrays.toString(arr2));
输出:
[1, 2, 3, 4, 5, 6, 7]
clone
通过源码可以看到该方法也是一个native方法,但其返回值为Object,因此赋值时会发生强转。其效率并不高
protected native Object clone() throws CloneNotSupportedException;
案例
int[] arr = {1,2,3,4,5,6,7};
int[] arr3 = arr.clone();
System.out.println(Arrays.toString(arr3));
输出:
[1, 2, 3, 4, 5, 6, 7]
在这四种方法中System.arraycopy是原生的,所以效率也是更高的。