Java陣列擴充套件

2019-10-16 22:31:02

在Java中,陣列初始化後如何擴充套件陣列?

範例

以下範例顯示如何在建立新並初始化陣列後擴充套件陣列。

package com.yiibai;

public class ExtendingArray {
    public static void main(String[] args) {
        String[] names = new String[] { "A", "B", "C" };
        String[] extended = new String[5];
        extended[3] = "D";
        extended[4] = "E";
        System.arraycopy(names, 0, extended, 0, names.length);

        for (String str : extended) {
            System.out.print(str+",");
        }
    }
}

執行上面範例程式碼,得到以下結果 -

A,B,C,D,E,

範例2

以下是陣列擴充套件的另一個範例範例 -

package com.yiibai;

public class ExtendingArray2 {
    public void extendArraySize() {
        String[] names = new String[] { "Maxsu", "Minsu", "Sum" };
        String[] extended = new String[5];
        extended[3] = "Sukida";
        extended[4] = "Avg";
        System.arraycopy(names, 0, extended, 0, names.length);

        for (String str : extended)
            System.out.println(str);
    }

    public static void main(String[] args) {
        new ExtendingArray2().extendArraySize();
    }
}

執行上面範例程式碼,得到以下結果 -

Maxsu
Minsu
Sum
Sukida
Avg