日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

java中arraycopy的用法_[jdk源码阅读系列]Java中System.arraycopy()的用法

發布時間:2024/7/23 java 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()的用法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。