[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; 
}

 

posted @ 2020-12-20 15:50  西伯利亚虎  阅读(394)  评论(0编辑  收藏  举报

Permanence, perseverance and persistence in spite of all obstacles, discouragements and impossibilities: It is this, that in all things distinguishes the strong soul from the weak.