選單

Java 中基本數組操作概述

目錄

在宣告數組的同時初始化數組。

你可以在宣告數組的同時初始化它,方法如下:

範例程式碼

static void arraySample() { String[] s = {"apple", "orange", "banana"}; } System.out.println(s[1]);

輸出結果:

橘子


取得數組中元素的數量。 尺寸

若要取得陣列中元素的數量,請使用 `length` 函數。請注意,`length` 是一個字段,而不是一個方法。

範例程式碼

static void lengthSample() {
    String[] s1 = {"りんご", "みかん", "ぶどう"};
    String[] s2 = {};
    System.out.println(s1.length);
    System.out.println(s2.length);
}

輸出結果:

3
0

複製數組 – 複製

如果你想要建立一個與另一個陣列完全相同的數組,`clone` 指令就很有用。

範例程式碼

static void cloneSample() { String[] s1 = {"apple", "orange", "grape"}; String[] s2 = s1.clone(); System.out.println(s1[0] + ' ' + s1[1] + ' ' + s1[2]); s2[2]); }

輸出結果:

蘋果、柳橙、葡萄、蘋果、柳橙、葡萄

複製數組 – 系統.數組複製

Java 陣列的大小在初始化時就已固定。如果想要在陣列建立後增加其大小,則需要使用 System.arraycopy 方法。

`arraycopy` 用於複製數組,就像 `clone` 一樣,但它允許比 `clone` 更詳細的配置。

arraycopy(Object src, int srcPos, Object dest, int destPos, int length) src... 要複製的陣列 srcPos... 從來源陣列 (src) 複製的起始位置 dest... 目標陣列 destPos...從目標陣列 (dest) 的起始位置

範例程式碼

static void arraycopySample() { String[] s1 = {"apple", "orange", "grape"}; String[] s2 = new String[5]; System.arraycopy(s1, 0, s2, 0, 3); s2[3]s = "band"ln); " " + s1[1] + " " + s1[2]); System.out.println(s2[0] + " " + s2[1] + " " + s2[2] + " " + s2[3] + " " + s2[4]); }

輸出結果:

蘋果、柳橙、葡萄、蘋果、柳橙、葡萄、香蕉、櫻桃

ArrayCopy 在連接陣列時也很有用。

範例程式碼

static void joinArraySample() {
    String[] s1 = {"りんご", "みかん", "ぶどう"};
    String[] s2 = {"ばなな", "さくらんぼ", "もも"};
    int rLen = s1.length + s2.length;
    String[] rStr = new String[rLen]; //s1とs2両方の長さ分の配列を初期化
    System.arraycopy(s1, 0, rStr, 0, s1.length);
    System.arraycopy(s2, 0, rStr, s1.length, s2.length); //コピー先配列の開始位置の設定がポイント
    System.out.println(rStr[0] + " " + rStr[1] + " " + rStr[2] + " " + rStr[3] + " " + rStr[4] + " " + rStr[5]);
}

輸出結果:

蘋果、柳橙、葡萄、香蕉、櫻桃、桃子

建立一個多維數組

透過在另一個數組中建立數組,您可以建立一個多維數組。例如,這在儲存表格資料時非常有用。

範例程式碼

static void twoDArraySample() { int[] a1 = {38, 84, 98}; int[] a2 = {32, 11, 56}; int[] a3 = {82, 77, 8}; int[][] twoD, fora); score : a) { System.out.print(score + " "); } System.out.println(""); } }

輸出結果:

38 84 98 
32 11 56 
82 77 8 
  • 網址をコピーしました!
目錄