System.arraycopy方法的使用

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, 1, 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, 1, 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));
    }

结果:

替换前arr2:[11, 22, 33, 44]
替换后arr2:[11, 22, bb, cc]
---------------
复制前arr3:[null, null, null, null]
复制后arr3:[null, aa, bb, null]

 

posted @ 2022-05-20 14:07  请别耽误我写BUG  阅读(610)  评论(0编辑  收藏  举报