System.arraycopy
首先观察 System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) 的实现方式:
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
- src - 源数组。
- srcPos - 源数组中的起始位置。
- dest - 目标数组。
- destPos - 目标数据中的起始位置。
- length - 要复制的数组元素的数量。
该方法是用了 native 关键字,调用的为 C++ 编写的底层函数,可见其为 JDK 中的底层函数。
System.arraycopy 是将元素复制到一个已经存在的数组。
Arrays.copyOf
// 非基本类型
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
// 基本数据类型:int、boolean、char、double 等
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;
}
Arrays.copyOf 是在其内部创建了一个相同类型的新数组,然后调用 System.arraycopy() 复制元素,最后返回出去的是这个新数组。
Arrays.copyOf 是浅拷贝
import java.util.Arrays;
class Person {
Person() {}
Person(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class ArrayCopyOfTest {
public static void main(String[] args) {
Person[] persons = new Person[3];
for (int i = 0; i < 3; i ++) {
persons[i] = new Person("name_" + i);
}
Person[] copyPersons = Arrays.copyOf(persons, 3);
copyPersons[0].setName("bnb");
for (int i = 0; i < 3; i ++) {
System.out.println(copyPersons[i].getName());
// bnb name_1 name_2
}
for (int i = 0; i < 3; i ++) {
System.out.println(persons[i].getName());
// bnb name_1 name_2
}
}
}