public class TestArrayMethod {
public static void main(String[] args) {
int score[] = {1,5,7,2,3,9,4,6,8};
getMax(score);
arraySort(score);
// 錯誤:在main方法內部定義方法!
public static void getMax(int arr[]) { ... }
public static void arraySort(int arr[]) { ... }
}
}
Illegal start of expression或modifier 'static' not allowed herepublic class TestArrayMethod {
// 主入口
public static void main(String[] args) {
int score[] = {1,5,7,2,3,9,4,6,8};
getMax(score);
arraySort(score);
}
// 類級別靜態方法:查找最大值
public static void getMax(int[] arr) {
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
}
System.out.println("數組score最大數:" + max);
}
// 類級別靜態方法:排序並打印
public static void arraySort(int[] arr) {
System.out.print("排序前的數組:");
printArray(arr);
Arrays.sort(arr); // 使用標準庫
System.out.print("\n排序後的數組:");
printArray(arr);
}
// 私有輔助方法:打印數組
private static void printArray(int[] arr) {
for (int v : arr) System.out.print(v + " ");
}
}
引用副本,指向同一堆內存arr[i]=x、Arrays.sort(arr))會影響原數組arr = new int[5])不影響原引用
main棧幀 堆內存
score ──────────────────→ [1,5,7,2,3,9,4,6,8]
↑
getMax/arraySort參數 arr ────┘ (引用副本指向同一對象)
| 操作 | 影響原數組 | 說明 |
|---|---|---|
| arr[i] = newValue | 是 | 修改堆上對象內容 |
| Arrays.sort(arr) | 是 | 原地排序修改對象 |
| arr = new int[10] | 否 | 參數引用指向新對象,原引用不變 |
| arr = null | 否 | 僅斷開參數引用 |
List<Integer>替代原始數組,API更豐富Stream API:Arrays.stream(arr).max().ifPresent(...)ArrayUtils類,遵循單一職責編譯錯誤源於方法嵌套定義違反Java語法。將方法提升至類級別即可修復。理解數組傳遞是「引用副本指向同一對象」,是掌握Java參數傳遞機制的關鍵。善用標準庫Arrays與Stream,寫出更簡潔健壯的代碼。