小千在给大家讲解数组扩容时,涉及到了数组中数据元素的拷贝复制。那么除了上面的拷贝方式之外,数组还有哪些拷贝方式呢?
1. 拷贝方式
在Java中,数组的拷贝主要有三种实现方式:
1. 通过循环语句,将原数组中的各个元素拷贝到新数组中(即数组扩容案例中使用的方法);
2. System类提供的数组拷贝方法;
3. Arrays类提供的数组拷贝方法。
接下来小千就设计几个案例,来给大家展示这几种方式都是怎么进行数组拷贝的。因为第一种数组拷贝方式,我们已经在数组扩容的案例中给大家演示了,这里就不再重复展示相关代码了。
2. System.arraycopy方法
2.1 简介
System.arraycopy()是Java提供的一个本地静态方法,用于将数据元素从源数组复制到目标数组。
public static native void arraycopy(Object src,int srcPos,Object dest,int destPos,int length);
arraycopy()方法有5个核心参数,其含义如下:
● src: 源数组,即被复制的旧数组;
● srcPos: 源数组中开始复制的索引位置;
● dest: 目标数组,即要复制到的新数组;
● destPos: 要复制到目标数组中的索位置;
● length: 要复制的元素个数。
另外我们还要注意,arraycopy()方法在有些情况下有可能会发生如下异常:
● NullPointerException: if source or destination array is null.NullPointerException :如果源或目标数组为null时,就会产生NullPointerException异常。
● ArrayStoreException: if the source and destination array type doesn’t match or they are not array.ArrayStoreException :如果源和目标数组类型不匹配或不是数组,会产生该异常;
● ArrayIndexOutOfBoundsException: if the data overflow occurs because of index values or they are negative.ArrayIndexOutOfBoundsException :如果由于索引值导致数据溢出,或它们为负数时会产生该异常。
2.2 案例
public class Demo07 {
public static void main(String[] args) {
// 数组拷贝
//1.源数组
int[] srcArr = {1,3,46,22,11};
//2.目标数组
int[] destArr = new int[srcArr.length + 5];
/**
* src:原数组
* srcPos:原数组的起始拷贝位置
* dest:目标数组
* destPos:目标数组的起始拷贝位置
* length:拷贝的长度
*/
//3.调用arraycopy方法进行复制
System.arraycopy(srcArr, 1, destArr, 3, 4);
//对新数组进行遍历
for (int i = 0; i < destArr.length; i++) {
System.out.print(destArr[i]+"\t");
}
}
}
3. Arrays.copyOf方法
3.1 简介
Arrays.copyOf()可以复制数组中指定范围的元素。该方法会返回一个新的数组对象,且改变新数组中的元素值,不会影响原来的数组。我们还可以利用Arrays.toString方法将赋值后的数组输出。
该方法支持的参数可以是long、float、double、int、boolean、byte、Object等类型的数组。
public static int[] copyOf(int[] original, int newLength);
copyOf()方法有2个核心参数,其含义如下:
● original: 源数组,即被复制的旧数组;
● newLength: 表示新数组的长度。如果新数组的长度超过源数组的长度,会采用数组元素类型的默认值。
3.2 案例
public class Demo08 {
public static void main(String[] args) {
// 数组拷贝
//1.源数组
int[] srcArr = {1,3,46,22,11};
/**
* original:原数组
* newLength:新数组的长度
* 返回值:返回新数组
*/
//2.调用copyOf方法进行数组拷贝
int[] destArr = Arrays.copyOf(srcArr, srcArr.length+1);
//3.遍历新数组
for (int i = 0; i < srcArr.length; i++) {
System.out.print(destArr[i]+"\t");
}
}
}