Effective Java~26. 不要使用 raw type
生活随笔
收集整理的這篇文章主要介紹了
Effective Java~26. 不要使用 raw type
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在編譯完成之后盡快發現錯誤是值得的,理想情況是在編譯時
在泛型被添加到 Java 之前,這是一個典型的集合聲明
// Raw collection type - don't do this! // My stamp collection. Contains only Stamp instances. private final Collection stamps = ... ;如果你今天使用這個聲明,然后不小心把 coin 實例放入你的 stamp 集合中,錯誤的插入編譯和運行沒有錯誤(盡管編譯器發出一個模糊的警告):
// Erroneous insertion of coin into stamp collection stamps.add(new Coin( ... )); // Emits "unchecked call" warning直到您嘗試從 stamp 集合中檢索 coin 實例時才會發生錯誤
// Raw iterator type - don't do this! for (Iterator i = stamps.iterator(); i.hasNext(); )Stamp stamp = (Stamp) i.next(); // Throws ClassCastExceptionstamp.cancel();例外
類字面值(class?literals)
List.class ,String[].class 和 int.class 都是合法的
List<String>.class 和 List<?>.class 不是合法的
instanceof?操作符
????????因為泛型類型信息在運行時被刪除,所以在無限制通配符類型以外的參數化類型上使用 instanceof 運算符是非法的
以下是使用泛型類型的instanceof 運算符的首選方法:
// Legitimate use of raw type - instanceof operator if (o instanceof Set) { // Raw typeSet<?> s = (Set<?>) o; // Wildcard type... }????????請注意,一旦確定 o 對象是一個 Set ,則必須將其轉換為通配符 Set<?> ,而不是原始類型 Set 。 這是一個強制轉換,所以不會導致編譯器警告。
為了快速參考,下表中總結了本條目(以及本章稍后介紹的一些)中介紹的術語:
| 術語 | 中文含義 | 舉例 | 所在條目 |
| Parameterized type | 參數化類型 | List<String> | 條目 26 |
| Actual type parameter | 實際類型參數 | String | 條目 26 |
| Generic type | 泛型類型 | List<E> | 條目 26 |
| Formal type parameter | 形式類型參數 | E | 條目 26 |
| Unbounded wildcard type | 無限制通配符類型 | List<?> | 條目 26 |
| Raw type | 原始類型 | List | 條目 26 |
| Bounded type parameter | 限制類型參數 | <E extends Number> | 條目 29 |
| Recursive type bound | 遞歸類型限制 | <T extends Comparable<T>> | 條目 30 |
| Bounded wildcard type | 限制通配符類型 | List<? extends Number> | 條目 31 |
| Generic method | 泛型方法 | static <E> List<E> asList(E[] a) | 條目 30 |
| Type token | 類型令牌 | String.class | 條目 33 |
總結
以上是生活随笔為你收集整理的Effective Java~26. 不要使用 raw type的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTML 显示特殊字符时转义操作
- 下一篇: java美元兑换,(Java实现) 美元