假設多新增了一個陣列 arrTwo

arrTwo 的值跟 arrOne 一模一樣

這時候除了用 for 迴圈一個一個 assign 外

也可以用 System 類別提供的靜態方法 arraycopy(),語法如下:

System.arraycopy(來源陣列,起始索引值,目的陣列,起始索引值,複製長度);

 

範例:

public class ArrCopy {
    public static void main(String[] args){
        int[] arrOne = new int[] {58, 1, 50, 23, 55, 78, 19, 3, 9, 29};
        int[] arrTwo = new int[arrOne.length];

        System.out.println("arrOne:");
        for(int e : arrOne){
            System.out.print(e+"  ");
        }


        System.arraycopy(arrOne, 0, arrTwo, 0, arrOne.length);

        System.out.println("\narrTwo:");
        for(int e : arrTwo){
            System.out.print(e+"  ");
        }

 

結果:

arrOne :
58  1  50  23  55  78  19  3  9  29 
arrTwo :
58  1  50  23  55  78  19  3  9  29

 

================================================================

System.arraycopy()這個方法必須要先自行建立一個明確的物件。

JDK 6 提供了另一種更方便的方法,利用 Arrays 類別的 copyOf() 方法,可以直接傳回一個新的陣列物件

語法如下:

Arrays.copy(要被複製的陣列,新陣列的長度);

新陣列的長度不一定要跟原陣列一樣,可以比原來的大,但不能比原來的小。

如果新陣列長度比原來的大,剩下的值會使用陣列型態預設值。

 

範例:

import java.util.Arrays;

public class ArrayCopy {
    public static void main(String[] args){
        int[] arrOne = new int[] {58,1,50,23,55,78,19,3,9,29};
        int[] arrThree = Arrays.copyOf(arrOne, arrOne.length);
        System.out.println("\narrThree after sorting : ");
        Arrays.sort(arrThree);
        for(int e : arrThree){
            System.out.print(e + "  ");
        }
    }
}

 

結果:

arrOne :
58  1  50  23  55  78  19  3  9  29 
arrThree after sorting :
1  3  9  19  23  29  50  55  58  78 

 

PS. Arrays.sort(arrThree) 是對 arrThree 作快速排序法

arrow
arrow
    全站熱搜

    toyangel 發表在 痞客邦 留言(3) 人氣()