| 問題 | 回答 |
|---|---|
| 陣列是類嗎? | 不是傳統意義的類,但它是引用型別,繼承自 java.lang.Object,實作 Cloneable、Serializable。 |
| 元素是物件嗎? | 視元素型別而定: • 基本型別陣列 (`int[]`) → 元素是基本值,非物件。 • 參考型別陣列 (`String[]`, `User[]`) → 元素是物件引用 (指標),指向堆上物件。 |
// 陣列隱含擁有的成員 (由 JVM 注入)
public final int length; // 唯一公開欄位
public Object clone(); // 淺層複製
// 繼承 Object 所有方法:toString(), equals(), hashCode()...
String[] arr = new String[3];
arr[0] = "Hello";
arr[1] = "World";
// 堆記憶體
+-----------------+ +-----------------+
| 陣列物件 | | 字串物件 "Hello" |
| length = 3 | | char[] value |
| [0] ────────────────→ | (字元陣列) |
| [1] ────────────────→ | 字串物件 "World"|
| [2] ──────→ null | +-----------------+
+-----------------+
// 基本型別 int[] 直接在陣列記憶體連續儲存 4-byte 整數,無額外物件
// 編譯期檢查
Object obj = new int[5]; // ✓ 陣列是 Object
Object obj2 = new String[5]; // ✓
// obj = new int(); // ✗ 基本型別不是 Object
// 執行期檢查
int[] arr = new int[3];
System.out.println(arr instanceof Object); // true
System.out.println(arr.getClass().isArray()); // true
System.out.println(arr.getClass().getComponentType()); // int