zoukankan      html  css  js  c++  java
  • 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(),参数少,不够灵活,只能指定复制的长度,无法设定偏移量

     

      

  • 相关阅读:
    移动端前端布局的必看前提
    单词统计
    用户场景分析
    学习进度(九)
    团队项目
    学习进度(二)
    数据可视化
    大二下,学习进度(一)
    求最大子数组的和
    构建之法3
  • 原文地址:https://www.cnblogs.com/xkaisun/p/4714254.html
Copyright © 2011-2022 走看看