學生最多選 3 門課。用 3 個獨立變數 course1, course2, course3 會導致:無法迴圈處理、無法動態知道已選幾門、程式碼重複。陣列將多個同類型變數打包成單一物件,支援索引存取與 length 查詢。
int[] 只能放 int,Course[] 只能放 Course (或子類)。int[] 本身是物件 (繼承 Object),變數存的是記憶體位址。// 推薦風格:型別[] 變數名
int[] scores;
Course[] courses;
// 建立 (指定長度)
scores = new int[5]; // {0,0,0,0,0}
courses = new Course[3]; // {null,null,null}
// 宣告同時給初值 (長度由元素個數決定)
int[] lucky = {7, 3, 9, 1};
String[] names = new String[] {"Alice", "Bob"}; // 匿名陣列
// 2D 陣列:3 列,每列長度不同 (鋸齒陣列)
int[][] matrix = new int[3][];
matrix[0] = new int[4];
matrix[1] = new int[5];
matrix[2] = new int[3];
matrix[0][0] = 10; // 存取
int[] arr = {10, 20, 30};
// 1. 傳統 for (需索引)
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
// 2. 增強 for (foreach) - 僅讀取,不需索引
for (int v : arr) {
System.out.println(v);
}
// 3. Java 8 Stream (函數式)
Arrays.stream(arr).forEach(System.out::println);
public class Student {
private String name;
private Course[] courses = new Course[3]; // 固定容量 3
private int count = 0; // 實際已選門數
public Student(String name) { this.name = name; }
public void chooseCourse(Course c) {
if (count < courses.length) {
courses[count++] = c;
System.out.println("已選:" + c.getTitle());
} else {
System.out.println("最多選 3 門!");
}
}
public Course[] getCourses() { return courses; } // 回傳整個陣列 (含 null)
public int getCount() { return count; }
}
| 特性 | 陣列 | ArrayList |
|---|---|---|
| 長度 | 固定 | 動態擴容 |
| 基本型別 | 直接支援 int[] | 需包裝類 Integer |
| 效能 | 極高 (連續記憶體) | 略低 (擴容複製) |
| API 豐富度 | 低 (只有 length) | 高 (add/remove/contains...) |
| 適用場景 | 長度固定、效能敏感、基本型別 | 長度不定、頻繁增刪、物件集合 |
arr.length() → 錯,陣列是 length 屬性,非方法。new int[3] = {1,2,3} → 錯,初始化列表只能用於宣告時。arr[3] (長度 3) → ArrayIndexOutOfBoundsException,索引 0~length-1。for (int v : arr) v = 99; → 無效,v 是複製值。型別[] 變數,建立 new 型別[長度] 或 {...}。for (int i=0; i 或 for (型別 v : arr)。 ArrayList (下一課介紹)。