正常学习的时候你是怎么拷贝或者复制数组的?
for循环挨个个赋值?java中提供了数组拷贝的方法,如下:
1.使用系统提供的类System.arraycopy
System.arraycopy(elements,0,data,0,elements.length);
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
src:源数组;
srcPos:源数组要复制的起始位置;
dest:目的数组;
destPos:目的数组放置的起始位置;
length:复制的长度。
注意:src and dest都必须是同类型或者可以进行转换类型的数组.
2.使用Arrays提供的方法Arrays.copyOf()
使用方法如下
int[] arr1 = {1, 2, 3, 4, 5}; int[] arr2 = Arrays.copyOf(arr1, 5); 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] + " "); }
下面是源码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; }
两者的区别在于,Arrays.copyOf()不仅仅只是拷贝数组中的元素,在拷贝元素时,会创建一个新的数组对象。而System.arrayCopy只拷贝已经存在数组元素。