// 錯誤嘗試:編譯通過,運行報 NullPointerException
public class IntArray2 {
int[] save;
public IntArray2(int initLen) {
save = new int[save.length]; // save 尚未初始化,save.length 拋 NPE
}
}
// 正確寫法:兩個構造函數,無參委託有參
public class IntArray2 {
int[] save;
public IntArray2() { this(10); } // 無參構造 -> 委託預設容量 10
public IntArray2(int initLen) { // 有參構造:真正初始化
if (initLen < 0) throw new IllegalArgumentException();
save = new int[initLen];
}
}
Java 物件創建流程:
錯誤代碼在構造函數體中讀取 `save.length`,此時 `save` 仍為 `null` → NPE。
this(...) 必須是構造函數第一條語句。
new IntArray2(); // 匹配無參構造 -> this(10) -> 有參構造(10)
new IntArray2(20); // 直接匹配有參構造(20)
new IntArray2(0); // 匹配有參構造(0) -> 拋異常 (依實現)
「實參傳或不傳不影響結果」是因為無參構造內部委託了固定值 10,若需無參時用 0,應改為 this(0)。
public class IntArray2 {
private int[] data;
private int size = 0;
public IntArray2() { this(16); } // 預設容量 16
public IntArray2(int capacity) {
if (capacity < 0) throw new IllegalArgumentException("Capacity < 0");
data = new int[capacity];
}
public void add(int value) {
ensureCapacity(size + 1);
data[size++] = value;
}
private void ensureCapacity(int minCap) {
if (minCap > data.length) {
int newCap = Math.max(data.length * 2, minCap);
data = Arrays.copyOf(data, newCap);
}
}
public int get(int index) { checkIndex(index); return data[index]; }
public int size() { return size; }
// ... 其他方法
}