System.arrayCopy的使用

首先看一下声明,这是一个native方法:

    // src - the source array
    // srcPos - starting position in the source array
    // dest - the destination array
    // destPos - starting position in the destination data
    // length - the number of array elements to be copied
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);


1. 测试自我复制

	int[] array = new int[] { 2, 3, 4, 5, 6 };
	System.out.println(Arrays.toString(array)); // [2, 3, 4, 5, 6]
	
	System.arraycopy(array, 1, array, 3, 2);
	System.out.println(Arrays.toString(array)); // [2, 3, 4, 3, 4]


2. 测试复制
	int[] array2 = new int[6];
	System.arraycopy(array, 1, array2, 0, 3);
	System.out.println(Arrays.toString(array2)); // [3, 4, 3, 0, 0, 0]


3. 测试数组越界

不越界的要求:
a. 源的起始位置 + 长度 <= 源的末尾
b. 目标的起始位置 + 长度 <= 目标的末尾
c. 且所有的参数 >= 0

		System.arraycopy(array, 0, array2, 0, array.length + 1); // java.lang.ArrayIndexOutOfBoundsException


4. 类型转换

源和目标数组的类型要一致:
a. 类型相同
b. 都是引用类型,并且可以转换

		Object[] array3 = new Object[] { 1, null, 3, 4.4, 5.1 };
		Integer[] array4 = new Integer[5];
		// ArrayStoreException would be thrown for copying the array whose component type is reference type
		// to the one whose component type is primitive type
		// int array 4 = new int[5];
		try {
			System.arraycopy(array3, 0, array4, 0, array3.length);
		} catch (ArrayStoreException e) {
			e.printStackTrace(); // java.lang.ArrayStoreException
		}
		System.out.println(Arrays.toString(array4)); // [1, null, 3, null, null]

可以看出,复制成功的部分会保留。

你可能感兴趣的:(java,array,copy,System,native)