复制数组的几种方式

遍历复制

​ 通过遍历数组,遍历的过程中把原数组中的数据复制到新的数组中

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是原生的,所以效率也是更高的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值