数组复制Arrays.copyOf与System.arraycopy的用法

方法简介:

Arrays.copyOf与System.arraycopy能够快速的复制数组,速度是for循环复制效率的两倍左右,原因就是其是native方法。


Arrays.copyOf:

需要传递两个参数:

 * @param original the array to be copied 需要复制的数组
 * @param newLength the length of the copy to be returned 需要复制数组的长度

方法使用代码:

int[] initArr = {
    
    1,2,3,4,5};
int[] targetArr = Arrays.copyOf(initArr,3);
for (int i : targetArr) {
    
    
	System.out.println("显示:"+i);
}

输出:

显示:1
显示:2
显示:3

System.arraycopy:

需要传递五个参数:
 * @param src  the source array. 需要copy的数组
 * @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. 复制的长度

方法使用代码:

int[] initArr = {
    
    1,2,3,4,5};
int[] finalArr = new int[4];
System.arraycopy(initArr,0,finalArr,0,4);
for (int i : finalArr) {
    
    
	System.out.println("显示:"+i);
}

输出:

显示:1
显示:2
显示:3
显示:4

猜你喜欢

转载自blog.csdn.net/weixin_43996353/article/details/114257845