java 之System.arraycopy() vs arrays.copyOf()
在java中,数组的复制可以有System.arraycopy与arrays.copyOf()两种选择,下面就详细介绍一下这两种方法的差别:
System.arraycopy
int[] src = {1,2,3,4,5}; int[] des = new int[10]; System.arraycopy(arr, 0, copied, 1, 5); //5 is the length to copy System.out.println(Arrays.toString(des));
输出结果:
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
arrays.copyOf()
int[] des= Arrays.copyOf(src, 10); //10 the the length of the new array System.out.println(Arrays.toString(des)); des= Arrays.copyOf(src, 3); System.out.println(Arrays.toString(des));
结果:
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0] [1, 2, 3]
本质区别:
System.arraycopy()更灵活,但是需要提前new个数组出来
arrays.copyOf(),参数少,不够灵活,只能指定复制的长度,无法设定偏移量