2. 배열 복사

2252 단어
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]

좋은 웹페이지 즐겨찾기