1. 程式人生 > >Arrays.coyOf()和System.arraycopy()的區別

Arrays.coyOf()和System.arraycopy()的區別

Arrays.coyOf()

public class Main {

    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4, 5};
        //這個方法含義:arr1複製到arr2 長度為8
        int[] arr2 = Arrays.copyOf(arr1, 8);
        System.out.println(Arrays.toString(arr2));

    }
}
//輸出結果:[1, 2, 3, 4, 5, 0, 0, 0]

System.arraycopy()


public class Main {

    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4, 5};
        //這個方法的含義:從arr1陣列索引3開始複製到2位到arr1從索引2
        System.arraycopy(arr1,3,arr1,2,2);  
        System.out.println(Arrays.toString(arr1));

    }
}