目录
1、Arrays.copyOf() 和 System.arrayCopy()
1.1、Arrays.copyOf()
1.2、System.arrayCopy()
1.3、区别
1、Arrays.copyOf() 和 System.arrayCopy()
1.1、Arrays.copyOf()
用于复制指定的数组内容以达到扩容的目的,该方法对不同的基本数据类型都有对应的重载方法,详见 java api:
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;
}
public static byte[] copyOf(byte[] original, int newLength) {
byte[] copy = new byte[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
从代码看,copyOf() 通过构造新的数组,调用System.arraycopy()将旧数组值拷贝到新数组中并返回。
Arrays.copyOf()方法返回的数组是新的数组对象,原数组对象仍是原数组对象,不变,该拷贝不会影响原来的数组。copyOf()的第二个自变量指定要建立的新数组长度,如果新数组的长度超过原数组的长度,则保留数组默认值。
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = Arrays.copyOf(arr1, 3);
int[] arr3 = Arrays.copyOf(arr1, 10);
for(int i = 0; i < arr2.length; i++)
System.out.print(arr2[i] + " ");
System.out.println();
for(int i = 0; i < arr3.length; i++)
System.out.print(arr3[i] + " ");
}
}
1 2 3
1 2 3 4 5 0 0 0 0 0
1.2、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中提供了一个native静态方法arraycopy(),可以使用这个方法来实现数组之间的复制。对于一维数组来说,这种复制属性值传递,修改副本不会影响原来的值。对于二维或者一维数组中存放的是对象时,复制结果是一维的引用变量传递给副本的一维数组,修改副本时,会影响原来的数组。参考:https://blog.csdn.net/qq_32440951/article/details/78357325
1.3、区别
Arrays.copyOf():不仅仅只是拷贝数组中的元素,在拷贝元素时,会创建一个新的数组对象。一般是将原数组元素按照原有顺序拷贝到新数组中。
System.arrayCopy只拷贝已经存在数组元素。