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

触摸阳光 2021-09-04 17:04:01 浏览数 (1398)
反馈

如果我们想复制一个数组,我们可以使用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.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 人点赞