2.数组的复制

1.System.arraycopy
底层提供的方法,所以该方法native修饰

   /*
    *
    * @param      src      the source array. 复制对象
    * @param      srcPos   starting position in the source array. 复制数据起始位置
    * @param      dest     the destination array. 目标数组
    * @param      destPos  starting position in the destination data. 目标数组起始位置
    * @param      length   the number of array elements to be copied. 复制个数
    * @exception  IndexOutOfBoundsException  if copying would cause
    *               access of data outside array bounds.
    * @exception  ArrayStoreException  if an element in the src
    *               array could not be stored into the dest array
    *               because of a type mismatch.
    * @exception  NullPointerException if either src or
    *               dest is null.
    */
   public static native void arraycopy(Object src,  int  srcPos,
                                       Object dest, int destPos,
                                       int length);

2.简单实现数组复制

    public static void main(String[] args) {
        Integer[] a = new Integer[]{1, 2, 3, 4};
        Integer[] a1 = new Integer[3];
        //从a下标1开始复制3个
        System.arraycopy(a, 1, a1, 0, a1.length);
        System.out.println(Arrays.asList(a1));
    }

输出结果

[2, 3, 4]

3.删除指定数组下标的元素

    public static void main(String[] args) {
//        Integer[] a = new Integer[]{1, 2, 3, 4};
//        Integer[] a1 = new Integer[3];
//        //从a下标1开始复制3个
//        System.arraycopy(a, 1, a1, 0, a1.length);
//        System.out.println(Arrays.asList(a1));
        Integer[] a = new Integer[]{1, 2, 3, 4};
//        System.arraycopy(a, 1, 1, 1, a.length - 1);
//        a[a.length - 1] = null;
        deleteIndex(a, 0);
        System.out.println(Arrays.asList(a));
    }

    public static void deleteIndex(Integer[] arr, int index) {
        int number = arr.length - 1 - index;
        System.arraycopy(arr, index+1, arr, index , number);
        System.out.println(Arrays.asList(arr));
        arr[arr.length - 1] = null;
    }

输出结果:

[2, 3, 4, 4]
[2, 3, 4, null]

你可能感兴趣的:(2.数组的复制)