浅拷贝
java中允许将一个数组变量拷贝到给另外一个数组变量。此时两个变量将引用一个数组。
初始化一个数组:int[] numbers = {1,2,3,4,5};
浅拷贝:int[] luckyNumbers = numbers;
两个数组的值引用对应同一个堆地址:
public class Main {
public static void main(String[] args) {
int[] numbers = new int[]{1, 2, 3, 4, 5};
System.out.println("原始数组:" + Arrays.toString(numbers));
int[] luckyNumbers = numbers;
System.out.println("浅拷贝数组:" + Arrays.toString(luckyNumbers));
luckyNumbers[3] = 1;
System.out.println("修改luckyNumbers之后的原始数组:" + Arrays.toString(numbers));
}
}
输出结果:
原始数组:[1, 2, 3, 4, 5]
浅拷贝数组:[1, 2, 3, 4, 5]
修改luckyNumbers之后的原始数组:[1, 2, 3, 1, 5]
深拷贝
数组的深拷贝就是将数组中的值全部拷贝到一个新的数组中
利用Arrays类的copyOf方法。
public class Main {
public static void main(String[] args) {
int[] numbers = new int[]{1, 2, 3, 4, 5};
System.out.println("原始数组:" + Arrays.toString(numbers));
int[] luckyNumbers = Arrays.copyOf(numbers, numbers.length);
System.out.println("深拷贝数组:" + Arrays.toString(luckyNumbers));
luckyNumbers[3] = 1;
System.out.println("修改luckyNumbers之后的原始数组:" + Arrays.toString(numbers));
}
}
输出结果:
原始数组:[1, 2, 3, 4, 5]
深拷贝数组:[1, 2, 3, 4, 5]
修改luckyNumbers之后的原始数组:[1, 2, 3, 4, 5]
可以看出,深拷贝只是将数组中的值传递过去,而没有传递引用。
Arrays.copyOf源码解析
public static int[] copyOf(@NotNull int[] original,@NotNull int newLength) {
int[] copy = new int[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
original:原始数组
newLength:拷贝新数组的长度
可以看出Arrays.copyOf方法其实还是调用了java原生态的一个方法System.arraycopy
System.arraycopy方法解析:
/**
* @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.
* @exception IndexOutOfBoundsException if copying would cause
* access of data outside array bounds.
* @exception ArrayStoreException if an element in the <code>src</code>
* array could not be stored into the <code>dest</code> array
* because of a type mismatch.
* @exception NullPointerException if either <code>src</code> or
* <code>dest</code> is <code>null</code>.
*/
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
- src:源数组
- srcPos:源数组起始位置
- dest:目标数组
- destPos:目标数组起始位置
- length:要复制的数组元素的长度。