Java中 System.arraycopy() 方法详解
本文翻译来源:原文出处
java中的System.arraycopy()方法是一个原生的静态方法,用来从源数组拷贝元素到目标数组中。
本章内容目录如下:
[TOC]
1. System.arraycopy() Method 方法参数
System.arraycopy() 方法如下:
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
- src: 源数组 .
- srcPos: 源数组中开始拷贝的索引值
- dest: 目标数组
- destPos: 拷贝到目标数组开始的索引值
- length: 拷贝元素的个数
2. Java System.arraycopy() 例子
一起来看看下面这些用该方法拷贝数组的例子。
public static void testSystemArrayCopyDemo() {
int[] srcArray = new int[]{1,2,3,4,5,6};
int[] desArray = new int[5];
System.arraycopy(srcArray,2,desArray,3,2);
System.out.println("desArray: " + Arrays.toString(desArray));
}
输出
desArray: [0, 0, 0, 3, 4]
从源数组中拷贝的是3,4.拷贝到目标数组开始拷贝的索引是3。
3. System.arraycopy() 当源数组和目标数组是同一个的时候
当源数组和目标数组是同一个时,会创建一个和源数组一样的临时数组,之后这个临时数组中的元素被拷贝到目标数组。
public static void testSystemArrayCopyDemo() {
int[] srcArray = new int[]{1,2,3,4,5,6};
int[] desArray = new int[5];
System.arraycopy(srcArray,2,srcArray,3,2);
System.out.println("desArray: " + Arrays.toString(srcArray));
}
输出
desArray: [1, 2, 3, 3, 4, 6]
4. System arraycopy() 方法的异常场景
arraycopy()方法有5个参数,因此,会有很多异常的实例,这个方法会抛出的方法如下:
- NullPointerException: 当源数组或者目标数组是null时。
- ArrayStoreException: 当源数组和目标数组的类型不匹配,或者根本就不是一个数组。
- ArrayIndexOutOfBoundsException: negative.当数据越界时,可能是因为索引的是负数。
一起看下一些异常场景的实例:
4.1. NullPointerException 当源数组或者目标数组是null时
public static void testSystemArrayCopyDemo() {
int[] srcArray = new int[]{1,2,3,4,5,6};
int[] desArray = new int[5];
System.arraycopy(null,2,srcArray,3,2);
}
4.2. ArrayStoreException当源数组和目标数组就不是个数组时
public static void testSystemArrayCopyDemo() {
int[] srcArray = new int[]{1,2,3,4,5,6};
int[] desArray = new int[5];
System.arraycopy("123",2,srcArray,3,2);
}
4.3. ArrayStoreException 当源数组和目标数组的类型不匹配时
public static void testSystemArrayCopyDemo() {
int[] srcArray = new int[]{1,2,3,4,5,6};
String[] desArray2 = new String[]{};
System.arraycopy(srcArray,2,desArray2,3,2);
}
4.4. ArrayIndexOutOfBoundsException 当索引或者长度是负数时
public static void testSystemArrayCopyDemo() {
int[] srcArray = new int[]{1,2,3,4,5,6};
int[] desArray = new int[5];
System.arraycopy(srcArray,-1,desArray,3,2);
}
4.5. ArrayIndexOutOfBoundsException 当开始拷贝的索引+长度 > 源数组的长度时
public static void testSystemArrayCopyDemo() {
int[] srcArray = new int[]{1,2,3,4,5,6};
int[] desArray = new int[5];
System.arraycopy(srcArray,5,desArray,3,6);
}
4.6. ArrayIndexOutOfBoundsException 当开始拷贝的索引+长度 > 目标数组的长度时
public static void testSystemArrayCopyDemo() {
int[] srcArray = new int[]{1,2,3,4,5,6};
int[] desArray = new int[5];
System.arraycopy(srcArray,0,desArray,3,6);
}
5.结论
System中的arraycopy()方法用来拷贝数组中的元素,可是,有很多的场景会导致发生运行时异常,所以,使用的时候要异常小心喽~~~