java中arraycopy的用法_[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;
}
總結
以上是生活随笔為你收集整理的java中arraycopy的用法_[jdk源码阅读系列]Java中System.arraycopy()的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python列表元素之和_python实
- 下一篇: java美元兑换,(Java实现) 美元