什麼是陣列?
陣列是一種儲存多個相同型別資料的容器。當我們需要儲存許多數字或字串時,可以使用陣列一次性地管理它們。
- ✅ 方便儲存多筆資料
- ✅ 可以用索引快速存取每一筆資料
舉例:
如果有五位學生的成績:90、85、78、92、88,
可以使用陣列:
1
| int[] scores = {90, 85, 78, 92, 88};
|
陣列的基本特性
| 特性 |
說明 |
| 固定大小 |
陣列大小在建立後不能更改 |
| 索引從 0 開始 |
第一個元素是 index 0,最後一個是 length - 1 |
| 相同型別 |
陣列中所有資料必須是同一種類型(int、String 等) |
1 2
| scores = {90, 85, 78, 92, 88} (長度為 5) [0] [1] [2] [3] [4]
|
如何建立陣列
1. 宣告陣列
1 2
| int[] numbers; String[] names;
|
2. 初始化陣列(給大小)
1
| int[] scores = new int[5];
|
3. 宣告 + 指定值
1 2
| int[] ages = {18, 20, 22}; String[] fruits = {"Apple", "Banana", "Cherry"};
|
存取與修改陣列資料
1 2
| System.out.println(ages[1]); ages[0] = 19;
|
索引從 0 開始,超出邊界會發生錯誤!
陣列的常見用途
1. 陣列遍歷(for 迴圈)
1 2 3
| for (int i = 0; i < scores.length; i++) { System.out.println(scores[i]); }
|
2. 陣列遍歷(for-each)
1 2 3
| for (int s : scores) { System.out.println(s); }
|
3. 計算平均值
1 2 3 4 5
| int total = 0; for (int s : scores) { total += s; } double avg = (double) total / scores.length;
|
4. 找出最大值
1 2 3 4
| int max = scores[0]; for (int s : scores) { if (s > max) max = s; }
|
字串與字元陣列
字元陣列 → 字串
1 2
| char[] letters = {'H', 'i'}; String word = new String(letters);
|
字串 → 字元陣列
1
| char[] chars = "Java".toCharArray();
|
多維陣列簡介(了解即可)
多維陣列其實是「陣列裡面裝陣列」,可以想成表格或矩陣。
1 2 3 4
| int[][] table = { {1, 2, 3}, {4, 5, 6} };
|
- 存取:
table[0][1] → 2
- 修改:
table[1][2] = 9;
遍歷:
1 2 3 4 5 6
| for (int i = 0; i < table.length; i++) { for (int j = 0; j < table[i].length; j++) { System.out.print(table[i][j] + " "); } System.out.println(); }
|