java中数组的复制方式

java中数组的复制方式

1、五种方式

  • for循环、
  • clone方法、
  • System.arraycopy方法、
  • Arrays.copyOf方法、
  • Arrays.copyOfRange方法。

2、示例

2.1、for循环

//源数组
int[] source = {10,30,20,40};
//目标数组
int[] target = new int[source.length];
for (int i = 0;i < source.length;i++){
    target[i] = source[i];
}

2.2、System.arraycopy()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-X9MUvOgT-1594724554994)(C:\Users\游建成\AppData\Roaming\Typora\typora-user-images\image-20200714185134904.png)]

public class ArrayCopyDemo{
   public static void main(String[] args){
     int[] a = {1,2,3,4};
     int[] b ={8,7,6,5,4,3,2,1};
     int[] c = {10,20};
     try{
        System.arraycopy(a, 0, b, 0, a.length);
        // 下面语句发生异常,目标数组c容纳不下原数组a的元素
        System.arraycopy(a, 0, c, 0, a.length);
     }catch(ArrayIndexOutOfBoundsException e){
        System.out.println(e);
     }
     for(int elem: b){
       System.out.print(elem+"  ");
     }
    
   }
}

2.3、Arrays.copyOf()、Arrays.copyOfRange()

Arrays.copyOf()
在这里插入图片描述

Arrays.copyOfRange()
在这里插入图片描述

// Arrays.copyOf()
int[] arr2 = new int[10000];
arr2 = Arrays.copyOf(arr, 10000);

// Arrays.copyOfRange()
int[] arr4 = new int[10000];
arr4 = Arrays.copyOfRange(arr, 0, 10000);

2.4、clone

public static void main(String[] args) { 
    int[] arr3 = new int[10000];
    arr3 = arr.clone();
}
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值