App下載

Java 中的 System.arraycopy() 與 Arrays.copyOf()

觸摸陽光 2021-09-04 17:04:01 瀏覽數(shù) (1965)
反饋

如果我們想復(fù)制一個數(shù)組,我們可以使用System.arraycopy()或Arrays.copyOf()。在這篇文章中,我使用一個簡單的例子來演示兩者之間的區(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));

輸出:

[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. 主要區(qū)別

不同之處在于Arrays.copyOf不僅復(fù)制元素,它還創(chuàng)建一個新數(shù)組。System.arrayCopy復(fù)制到現(xiàn)有數(shù)組中。

如果我們閱讀?Arrays.copyOf()?的源代碼,我們可以看到它使用?System.arraycopy()?.

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


0 人點(diǎn)贊