陣列是每門程式語言的重要資料結構之一,Java 提供的陣列用於儲存固定大小的同類型元素。當需要保存一組相同類型的變數或物件時,使用陣列能避免程式碼臃腫。陣列分為一維、二維和多維陣列,本文將系統介紹陣列的宣告、建立、初始化及常見處理技巧。
使用陣列前必須先宣告,語法如下:
type[] 陣列名;type 陣列名[];(效果相同但不符合 Java 慣例)注意: 宣告時不能指定長度(元素個數)。
Java 使用 new 關鍵字建立陣列:
type[] 陣列名 = new type[元素個數]; // 例:int[] a = new int[3];
陣列名實際指向陣列元素的首地址。
type[] 變數名 = new type[]{元素1, 元素2, ...};
// 可簡寫為:type[] 變數名 = {元素1, 元素2, ...};
注意: 使用大括號初始化時,第二個方括號不能指定長度,長度由大括號內元素個數決定。
每個陣列都有 length 屬性(public final int),表示陣列長度,一旦確定無法改變。
// 靜態初始化
int[][] table = new int[][] { { 1, 2, 3 }, { 4, 5, 6 }, { 5, 6, 3 } };
// 動態建立再賦值
int[][] table2 = new int[3][3];
table2[0][0] = 11;
table2[0][1] = 121;
// ... 其餘賦值
// 遍歷二維陣列
for (int row = 0; row < table.length; row++) {
for (int col = 0; col < table[row].length; col++) {
System.out.print(table[row][col] + "\t");
}
System.out.println();
}
// 動態初始化
int[] a = new int[3];
a[0] = 0; a[1] = 1; a[2] = 2;
String[] str = new String[3];
str[0] = "張三"; str[1] = "李四"; str[2] = "小明";
// 靜態初始化
int[] b = {0, 1, 2};
String[] str2 = {"張三", "李四", "小敏"};
// 預設初始化
int[] c = new int[5];
System.out.println(c[3]); // 輸出 0
陣列元素與大小固定,處理時通常使用基本 for 迴圈或增強 for 迴圈(JDK 1.5+)。
double[] list = {1.9, 2.9, 3.4, 3.5};
// 列印所有元素
for (int i = 0; i < list.length; i++) {
System.out.println(list[i] + " ");
}
// 計算總和
double total = 0;
for (int i = 0; i < list.length; i++) {
total += list[i];
}
System.out.println("Total is " + total);
// 找最大值
double max = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] > max) max = list[i];
}
System.out.println("Max is " + max);
int[] list = {1, 9, 2, 9, 3, 4, 3, 5};
for (int num : list) {
System.out.println(num);
}
// copyOf 範例
int[] a = {2, 5, 2, 2, 2, 6, 2, 3};
int[] b = Arrays.copyOf(a, a.length);
// copyOfRange 範例:複製索引 0 到 2(不含 3)
int[] c = Arrays.copyOfRange(a, 0, 3); // 結果:[2, 5, 2]
int[] arr = {2, 4, 2, 77, 22, 777, 34};
Arrays.sort(arr);
// 結果:[2, 2, 4, 22, 34, 77, 777]
利用 Random 與布林旗標檢查重複,重複則重新產生:
Random rd = new Random();
int[] numbers = new int[5];
int index = 0;
for (int i = 1; i <= 5; i++) {
int num = rd.nextInt(5) + 1; // 1-5
boolean duplicate = false;
for (int j = 0; j < index; j++) {
if (numbers[j] == num) { duplicate = true; break; }
}
if (!duplicate) numbers[index++] = num;
else i--; // 重試
}
Arrays.equals(a, b):兩個陣列順序與元素完全相同才回傳 true;皆為 null 也視為相等。
int[] a = {2, 4, 2, 77, 22, 777, 34};
int[] b = {2, 4, 2, 77, 22, 777, 34};
int[] c = {4, 2, 22, 77, 2, 777, 34};
System.out.println(Arrays.equals(a, b)); // true
System.out.println(Arrays.equals(a, c)); // false
