java中arraycopy的用法_[jdk源码阅读系列]Java中System.arraycopy()的用法
本文轉(zhuǎn)載,原文鏈接:
3分鐘了解Java中System.arraycopy的用法 - 伊萬(wàn)夫斯基 - 博客園? https://www.cnblogs.com/benjieqiang/p/11428832.html
3分鐘了解Java中System.arraycopy的用法
System提供了一個(gè)靜態(tài)方法arraycopy(),我們可以使用它來(lái)實(shí)現(xiàn)數(shù)組之間的復(fù)制。其函數(shù)原型是:
public static native void arraycopy(Object src,int srcPos,Object dest, int destPos,int length);
*@param src the source array. 源數(shù)組*@param srcPos starting position in the source array. 源數(shù)組的起始位置*@param dest the destination array. 目標(biāo)數(shù)組*@param destPos starting position in the destination data. 目標(biāo)數(shù)組的起始位置* @param length the number of array elements to be copied. 復(fù)制的長(zhǎng)度
舉個(gè)栗子:
將array數(shù)組復(fù)制到新的數(shù)組中;
int[] array = {1, 2, 3, 4, 5};int[] targetArr = new int[array.length];
System.arraycopy(array,0,targetArr,0,array.length);
本文轉(zhuǎn)載,原文鏈接:
Java-Java中System.arraycopy() 和 Arrays.copyOf()兩者之間的區(qū)別 - 夜行過(guò)客 - 博客園? https://www.cnblogs.com/yongdaimi/p/5995414.html
Java-Java中System.arraycopy() 和 Arrays.copyOf()兩者之間的區(qū)別
如果我們想拷貝一個(gè)數(shù)組,我們可能會(huì)使用System.arraycopy()或者Arrays.copyof()兩種方式。在這里,我們將使用一個(gè)比較簡(jiǎn)單的示例來(lái)闡述兩者之間的區(qū)別。
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));
運(yùn)行結(jié)果:
[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));
運(yùn)行結(jié)果:
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[1, 2, 3]
2、兩者間的主要區(qū)別
兩者的區(qū)別在于,Arrays.copyOf()不僅僅只是拷貝數(shù)組中的元素,在拷貝元素時(shí),會(huì)創(chuàng)建一個(gè)新的數(shù)組對(duì)象。而System.arrayCopy只拷貝已經(jīng)存在數(shù)組元素。
如果我們看過(guò)Arrays.copyOf()的源碼就會(huì)知道,該方法的底層還是調(diào)用了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;
}
總結(jié)
以上是生活随笔為你收集整理的java中arraycopy的用法_[jdk源码阅读系列]Java中System.arraycopy()的用法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python列表元素之和_python实
- 下一篇: 曲线积分与曲面积分总结_高数下册||知识