zoukankan      html  css  js  c++  java
  • [jdk源码阅读系列]Java中System.arraycopy()的用法

    本文转载,原文链接

    3分钟了解Java中System.arraycopy的用法 - 伊万夫斯基 - 博客园  https://www.cnblogs.com/benjieqiang/p/11428832.html

    3分钟了解Java中System.arraycopy的用法

     System提供了一个静态方法arraycopy(),我们可以使用它来实现数组之间的复制。其函数原型是:

    public static native void arraycopy(Object src,int srcPos,Object dest, int destPos,int length);
    * @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. 复制的长度

    举个栗子:

    将array数组复制到新的数组中;

    int[] array = {1, 2, 3, 4, 5};
    int[] targetArr = new int[array.length];
    System.arraycopy(array,0,targetArr,0,array.length);

    本文转载,原文链接

    Java-Java中System.arraycopy() 和 Arrays.copyOf()两者之间的区别 - 夜行过客 - 博客园  https://www.cnblogs.com/yongdaimi/p/5995414.html

    Java-Java中System.arraycopy() 和 Arrays.copyOf()两者之间的区别

    如果我们想拷贝一个数组,我们可能会使用System.arraycopy()或者Arrays.copyof()两种方式。在这里,我们将使用一个比较简单的示例来阐述两者之间的区别。

    1、示例代码:

    System.arraycopy()

    int[] arr = {1,2,3,4,5};
     
    int[] copied = new int[10];
    System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy
     
    System.out.println(Arrays.toString(copied));

    运行结果:

    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    [0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

    Arrays.copyof()

    int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array
    System.out.println(Arrays.toString(copied));
     
    copied = Arrays.copyOf(arr, 3);
    System.out.println(Arrays.toString(copied));

    运行结果:

    [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
    [1, 2, 3]

    2、两者间的主要区别

    两者的区别在于,Arrays.copyOf()不仅仅只是拷贝数组中的元素,在拷贝元素时,会创建一个新的数组对象。而System.arrayCopy只拷贝已经存在数组元素。

    如果我们看过Arrays.copyOf()的源码就会知道,该方法的底层还是调用了System.arrayCopyOf()方法。

    public static int[] copyOf(int[] original, int newLength) { 
       int[] copy = new int[newLength]; 
       System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); 
       return copy; 
    }
  • 相关阅读:
    Logstash利用GeoIP库显示地图以及通过useragent显示浏览器(
    remote tomcat monitor---jmc--jvisualvm
    python AI(numpy,matplotlib)
    rpm package.http://rpmfind.net/
    cpuspeed和irqbalance服务器的两大性能杀手
    什么叫CallBack函数,怎么用回调函数?
    发送微博消息
    curl抓取信息
    JavaScript键盘事件全面控制代码
    js实现网页收藏功能,动态添加删除网址
  • 原文地址:https://www.cnblogs.com/tongongV/p/13907077.html
Copyright © 2011-2022 走看看