聲明 ArrayList 可 foreach 遍歷;去掉泛型 ArrayList list 則編譯報錯:incompatible types: Object cannot be converted to String。
// 源碼
for (String s : list) { ... }
// 編譯器生成 (JDK 5+)
Iterator it = list.iterator(); // 泛型情況:Iterator
while (it.hasNext()) {
String s = it.next(); // 直接賦值,無需強轉
...
}
// 無泛型情況
Iterator it = list.iterator(); // 原始類型 Iterator
while (it.hasNext()) {
String s = it.next(); // 編譯錯誤:it.next() 返回 Object
// 必須手動強轉:String s = (String) it.next();
}
| 作用 | 說明 | 示例 |
|---|---|---|
| **類型安全** | 編譯期捕獲類型錯誤,避免運行時 ClassCastException | List |
| **消除強轉** | 編譯器自動插入檢查轉換,代碼更乾淨 | foreach、流式 API 直接獲得正確類型 |
| **代碼復用** | 同一邏輯適用多種類型 | class Box<T> { T value; } |