Java 基础——System.arraycopy() 与 Arrays.copyOf() 的联系与区别

1.System.arraycopy()

(1)查看源码可知, System.arraycopy() 是一个 native 方法,其各项参数介绍如下:

public final class System {
	
	//...
	
	/*
	 * @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);	
}

(2)测试

class ArrayCopyTest {
    public static void main(String[] args) {
        int[] src = new int[4];
        src[0] = 0;
        src[1] = 1;
        src[2] = 2;
        src[3] = 3;
        int[] desc = new int[10];
        System.out.println("复制之前,desc 中的元素如下");
        for (int elem : desc) {
            System.out.print(elem + " ");
        }
        System.arraycopy(src, 0, desc, 5, 4);
        System.out.println("\n\n复制之后,desc 中的元素如下");
        for (int elem : desc) {
            System.out.print(elem + " ");
        }
    }
}

输出结果如下:

复制之前,desc 中的元素如下
0 0 0 0 0 0 0 0 0 0 

复制之后,desc 中的元素如下
0 0 0 0 0 0 1 2 3 0 

2.Arrays.copyOf()

(1)copyOf() 是 Arrays 类中的一个静态方法,其源码如下所示:

public class Arrays {
	
	//...
	
	/*
	 * @param original the array to be copied
     * @param newLength the length of the copy to be returned
     * @return a copy of the original array, truncated or padded with zeros
     *     to obtain the specified length
     */
    public static int[] copyOf(int[] original, int newLength) {
        int[] copy = new int[newLength];
        //调用 System.arraycopy() ,将源数组中的数据进行拷, 并返回新的数组
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
}

(2)测试

class ArrayCopyTest {
    public static void main(String[] args) {
        int[] original = new int[4];
        original[0] = 0;
        original[1] = 1;
        original[2] = 2;
        original[3] = 3;
        int[] desc = Arrays.copyOf(original, 10);
        for (int elem : desc) {
            System.out.print(elem + " ");
        }
    }
}

输出结果如下:

0 1 2 3 0 0 0 0 0 0 

3.联系与区别

(1)联系:看两者源代码可以发现 copyOf() 内部实际调用了 System.arraycopy() 方法。

(2)区别:arraycopy() 需要目标数组,将原数组拷贝到你自己定义的数组里或者原数组,而且可以选择拷贝的起点和长度以及放入新数组中的位置 copyOf() 是系统自动在内部新建一个数组,并返回该数组。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码星辰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值