System.arraycopy:
一般用于数组的复制和数据替换,是System类中一个被关键词native修饰的方法。
源码:
public static native void arraycopy(Object src, int srcPos, Object dest,
int destPos,
int length);
解释:
src:数据源,被复制的对象
srcPos:复制起始坐标
dest:目标对象
destPos:目标对象开始复制的起始点
length:复制的数据长度
举例:
给出数据源数组:String[] arr1 = {"aa", "bb", "cc", "dd"};
目标1:String[] arr2 = {"11", "22", "33", "44"};
要求:用arr1中的"bb","cc"替换arr2中的"33","44"
则实现方式为:System.arraycopy(arr1, 2, arr2, 2, 2);
目标2:String[] arr3 = new String[4];
要求:把arr1中的“aa”,"bb"复制到arr3的arr2[1],arr2[2]
则实现方式为:System.arraycopy(arr1, 0, arr2, 1, 2);
验证:
public static void main(String[] args) { String[] arr1 = {"aa", "bb", "cc", "dd"}; String[] arr2 = {"11", "22", "33", "44"}; String[] arr3 = new String[4]; System.out.println("替换前arr2:" + Arrays.toString(arr2)); System.arraycopy(arr1, 2, arr2, 2, 2); System.out.println("替换后arr2:" + Arrays.toString(arr2)); System.out.println("---------------"); System.out.println("复制前arr3:" + Arrays.toString(arr3)); System.arraycopy(arr1, 0, arr3, 1, 2); System.out.println("复制后arr3:" + Arrays.toString(arr3)); }