## Chapter 5. Generics(泛型)
### Item 28: Prefer lists to arrays(list 優于數組)
Arrays differ from generic types in two important ways. First, arrays are covariant. This scary-sounding word means simply that if Sub is a subtype of Super, then the array type Sub[] is a subtype of the array type Super[]. Generics, by contrast, are invariant: for any two distinct types Type1 and Type2, `List<Type1>` is neither a subtype nor a supertype of `List<Type2>` [JLS, 4.10; Naftalin07, 2.5]. You might think this means that generics are deficient, but arguably(可能,大概) it is arrays that are deficient. This code fragment is legal:
數組與泛型有兩個重要區別。首先,數組是協變的。這個聽起來很嚇人的單詞的意思很簡單,如果 Sub 是 Super 的一個子類型,那么數組類型 Sub[] 就是數組類型 Super[] 的一個子類型。相比之下,泛型是不變的:對于任何兩個不同類型 Type1 和 Type2,`List<Type1>` 既不是 `List<Type2>` 的子類型,也不是 `List<Type2>` 的超類型 [JLS, 4.10; Naftalin07, 2.5]。你可能認為這意味著泛型是有缺陷的,但可以說數組才是有缺陷的。這段代碼是合法的:
```
// Fails at runtime!
Object[] objectArray = new Long[1];
objectArray[0] = "I don't fit in"; // Throws ArrayStoreException
```
but this one is not:
但這一段代碼就不是:
```
// Won't compile!
List<Object> ol = new ArrayList<Long>(); // Incompatible types
ol.add("I don't fit in");
```
Either way you can’t put a String into a Long container, but with an array you find out that you’ve made a mistake at runtime; with a list, you find out at compile time. Of course, you’d rather find out at compile time.
兩種方法都不能將 String 放入 Long 容器,但使用數組,你會得到一個運行時錯誤;使用 list,你可以在編譯時發現問題。當然,你更希望在編譯時找到問題。
The second major difference between arrays and generics is that arrays are reified [JLS, 4.7]. This means that arrays know and enforce their element type at runtime. As noted earlier, if you try to put a String into an array of Long, you’ll get an ArrayStoreException. Generics, by contrast, are implemented by erasure [JLS, 4.6]. This means that they enforce their type constraints only at compile time and discard (or erase) their element type information at runtime. Erasure is what allowed generic types to interoperate freely with legacy code that didn’t use generics (Item 26), ensuring a smooth transition to generics in Java 5.
數組和泛型之間的第二個主要區別:數組是具體化的 [JLS, 4.7]。這意味著數組在運行時知道并強制執行他們的元素類型。如前所述,如果試圖將 String 元素放入一個 Long 類型的數組中,就會得到 ArrayStoreException。相比之下,泛型是通過擦除來實現的 [JLS, 4.6]。這意味著它們只在編譯時執行類型約束,并在運行時丟棄(或擦除)元素類型信息。擦除允許泛型與不使用泛型的遺留代碼自由交互操作([Item-26](/Chapter-5/Chapter-5-Item-26-Do-not-use-raw-types.md)),確保在 Java 5 中平穩地過渡。
Because of these fundamental differences, arrays and generics do not mix well. For example, it is illegal to create an array of a generic type, a parameterized type, or a type parameter. Therefore, none of these array creation expressions are legal: `new List<E>[]`, `new List<String>[]`, `new E[]`. All will result in generic array creation errors at compile time.
由于這些基本差異,數組和泛型不能很好地混合。例如,創建泛型、參數化類型或類型參數的數組是非法的。因此,這些數組創建表達式都不是合法的:`new List<E>[]`、`new List<String>[]`、`new E[]`。所有這些都會在編譯時導致泛型數組創建錯誤。
Why is it illegal to create a generic array? Because it isn’t typesafe. If it were legal, casts generated by the compiler in an otherwise correct program could fail at runtime with a ClassCastException. This would violate the fundamental guarantee provided by the generic type system.
為什么創建泛型數組是非法的?因為這不是類型安全的。如果合法,編譯器在其他正確的程序中生成的強制轉換在運行時可能會失敗,并導致 ClassCastException。這將違反泛型系統提供的基本保證。
To make this more concrete, consider the following code fragment:
為了更具體,請考慮以下代碼片段:
```
// Why generic array creation is illegal - won't compile!
List<String>[] stringLists = new List<String>[1]; // (1)
List<Integer> intList = List.of(42); // (2)
Object[] objects = stringLists; // (3)
objects[0] = intList; // (4)
String s = stringLists[0].get(0); // (5)
```
Let’s pretend that line 1, which creates a generic array, is legal. Line 2 creates and initializes a `List<Integer>` containing a single element. Line 3 stores the `List<String>` array into an Object array variable, which is legal because arrays are covariant. Line 4 stores the `List<Integer>` into the sole element of the Object array, which succeeds because generics are implemented by erasure: the runtime type of a `List<Integer>` instance is simply List, and the runtime type of a `List<String>`[] instance is List[], so this assignment doesn’t generate an ArrayStoreException. Now we’re in trouble. We’ve stored a `List<Integer>` instance into an array that is declared to hold only `List<String>` instances. In line 5, we retrieve the sole element from the sole list in this array. The compiler automatically casts the retrieved element to String, but it’s an Integer, so we get a ClassCastException at runtime. In order to prevent this from happening, line 1 (which creates a generic array) must generate a compile-time error.
假設創建泛型數組的第 1 行是合法的。第 2 行創建并初始化一個包含單個元素的 `List<Integer>`。第 3 行將 `List<String>` 數組存儲到 Object 類型的數組變量中,這是合法的,因為數組是協變的。第 4 行將 `List<Integer>` 存儲到 Object 類型的數組的唯一元素中,這是成功的,因為泛型是由擦除實現的:`List<Integer>` 實例的運行時類型是 List,`List<String>`[] 實例的運行時類型是 List[],因此這個賦值不會生成 ArrayStoreException。現在我們有麻煩了。我們將一個 `List<Integer>` 實例存儲到一個數組中,該數組聲明只保存 `List<String>` 實例。在第 5 行,我們從這個數組的唯一列表中檢索唯一元素。編譯器自動將檢索到的元素轉換為 String 類型,但它是一個 Integer 類型的元素,因此我們在運行時得到一個 ClassCastException。為了防止這種情況發生,第 1 行(創建泛型數組)必須生成編譯時錯誤。
Types such as E, `List<E>`, and `List<String>` are technically known as nonreifiable types [JLS, 4.7]. Intuitively speaking, a non-reifiable type is one whose runtime representation contains less information than its compile-time representation. Because of erasure, the only parameterized types that are reifiable are unbounded wildcard types such as `List<?>` and `Map<?,?>` (Item 26). It is legal, though rarely useful, to create arrays of unbounded wildcard types.
E、`List<E>` 和 `List<string>` 等類型在技術上稱為不可具體化類型 [JLS, 4.7]。直觀地說,非具體化類型的運行時表示包含的信息少于其編譯時表示。由于擦除,唯一可具體化的參數化類型是無限制通配符類型,如 `List<?>` 和 `Map<?,?>`([Item-26](/Chapter-5/Chapter-5-Item-26-Do-not-use-raw-types.md))。創建無邊界通配符類型數組是合法的,但不怎么有用。
The prohibition on generic array creation can be annoying. It means, for example, that it’s not generally possible for a generic collection to return an array of its element type (but see Item 33 for a partial solution). It also means that you get confusing warnings when using varargs methods (Item 53) in combination with generic types. This is because every time you invoke a varargs method, an array is created to hold the varargs parameters. If the element type of this array is not reifiable, you get a warning. The SafeVarargs annotation can be used to address this issue (Item 32).
禁止創建泛型數組可能很煩人。例如,這意味著泛型集合通常不可能返回其元素類型的數組(部分解決方案請參見 [Item-33](/Chapter-5/Chapter-5-Item-33-Consider-typesafe-heterogeneous-containers.md))。這也意味著在使用 varargs 方法([Item-53](/Chapter-8/Chapter-8-Item-53-Use-varargs-judiciously.md))與泛型組合時,你會得到令人困惑的警告。這是因為每次調用 varargs 方法時,都會創建一個數組來保存 varargs 參數。如果該數組的元素類型不可具體化,則會得到警告。SafeVarargs 注解可以用來解決這個問題([Item-32](/Chapter-5/Chapter-5-Item-32-Combine-generics-and-varargs-judiciously.md))。
**譯注:varargs 方法,指帶有可變參數的方法。**
When you get a generic array creation error or an unchecked cast warning on a cast to an array type, the best solution is often to use the collection type `List<E>` in preference to the array type E[]. You might sacrifice some conciseness or performance, but in exchange you get better type safety and interoperability.
當你在轉換為數組類型時遇到泛型數組創建錯誤或 unchecked 強制轉換警告時,通常最好的解決方案是使用集合類型 `List<E>`,而不是數組類型 E[]。你可能會犧牲一些簡潔性或性能,但作為交換,你可以獲得更好的類型安全性和互操作性。
For example, suppose you want to write a Chooser class with a constructor that takes a collection, and a single method that returns an element of the collection chosen at random. Depending on what collection you pass to the constructor, you could use a chooser as a game die, a magic 8-ball, or a data source for a Monte Carlo simulation. Here’s a simplistic implementation without generics:
例如,假設你希望編寫一個 Chooser 類,該類的構造函數接受一個集合,而單個方法返回隨機選擇的集合元素。根據傳遞給構造函數的集合,可以將選擇器用作游戲骰子、魔術 8 球或蒙特卡洛模擬的數據源。下面是一個沒有泛型的簡單實現:
```
// Chooser - a class badly in need of generics!
public class Chooser {
private final Object[] choiceArray;
public Chooser(Collection choices) {
choiceArray = choices.toArray();
}
public Object choose() {
Random rnd = ThreadLocalRandom.current();
return choiceArray[rnd.nextInt(choiceArray.length)];
}
}
```
To use this class, you have to cast the choose method’s return value from Object to the desired type every time you use invoke the method, and the cast will fail at runtime if you get the type wrong. Taking the advice of Item 29 to heart, we attempt to modify Chooser to make it generic. Changes are shown in boldface:
要使用這個類,每次使用方法調用時,必須將 choose 方法的返回值從對象轉換為所需的類型,如果類型錯誤,轉換將在運行時失敗。我們認真考慮了 [Item-29](/Chapter-5/Chapter-5-Item-29-Favor-generic-types.md) 的建議,試圖對 Chooser 進行修改,使其具有通用性。變化以粗體顯示:
```
// A first cut at making Chooser generic - won't compile
public class Chooser<T> {
private final T[] choiceArray;
public Chooser(Collection<T> choices) {
choiceArray = choices.toArray();
}
// choose method unchanged
}
```
If you try to compile this class, you’ll get this error message:
如果你嘗試編譯這個類,你將得到這樣的錯誤消息:
```
Chooser.java:9: error: incompatible types: Object[] cannot be converted to T[]
choiceArray = choices.toArray();
^ where T is a type-variable:
T extends Object declared in class Chooser
```
No big deal, you say, I’ll cast the Object array to a T array:
沒什么大不了的,你會說,我把對象數組轉換成 T 數組:
```
choiceArray = (T[]) choices.toArray();
```
This gets rid of the error, but instead you get a warning:
這樣就消除了錯誤,但你得到一個警告:
```
Chooser.java:9: warning: [unchecked] unchecked cast choiceArray = (T[]) choices.toArray();
^ required: T[], found: Object[]
where T is a type-variable:
T extends Object declared in class Chooser
```
The compiler is telling you that it can’t vouch for the safety of the cast at runtime because the program won’t know what type T represents—remember, element type information is erased from generics at runtime. Will the program work? Yes, but the compiler can’t prove it. You could prove it to yourself, put the proof in a comment and suppress the warning with an annotation, but you’re better off eliminating the cause of warning (Item 27).
編譯器告訴你,它不能保證在運行時轉換的安全性,因為程序不知道類型 T 代表什么。記住,元素類型信息在運行時從泛型中刪除。這個計劃會奏效嗎?是的,但是編譯器不能證明它。你可以向自己證明這一點,但是你最好將證據放在注釋中,指出消除警告的原因([Item-27](/Chapter-5/Chapter-5-Item-27-Eliminate-unchecked-warnings.md)),并使用注解隱藏警告。
To eliminate the unchecked cast warning, use a list instead of an array. Here is a version of the Chooser class that compiles without error or warning:
若要消除 unchecked 強制轉換警告,請使用 list 而不是數組。下面是編譯時沒有錯誤或警告的 Chooser 類的一個版本:
```
// List-based Chooser - typesafe
public class Chooser<T> {
private final List<T> choiceList;
public Chooser(Collection<T> choices) {
choiceList = new ArrayList<>(choices);
}
public T choose() {
Random rnd = ThreadLocalRandom.current();
return choiceList.get(rnd.nextInt(choiceList.size()));
}
}
```
This version is a tad more verbose, and perhaps a tad slower, but it’s worth it for the peace of mind that you won’t get a ClassCastException at runtime.
這個版本稍微有點冗長,可能稍微慢一些,但是為了讓你安心,在運行時不會得到 ClassCastException 是值得的。
In summary, arrays and generics have very different type rules. Arrays are covariant and reified; generics are invariant and erased. As a consequence, arrays provide runtime type safety but not compile-time type safety, and vice versa for generics. As a rule, arrays and generics don’t mix well. If you find yourself mixing them and getting compile-time errors or warnings, your first impulse should be to replace the arrays with lists.
總之,數組和泛型有非常不同的類型規則。數組是協變的、具體化的;泛型是不變的和可被擦除的。因此,數組提供了運行時類型安全,而不是編譯時類型安全,對于泛型反之亦然。一般來說,數組和泛型不能很好地混合。如果你發現將它們混合在一起并得到編譯時錯誤或警告,那么你的第一個反應該是將數組替換為 list。
---
**[Back to contents of the chapter(返回章節目錄)](/Chapter-5/Chapter-5-Introduction.md)**
- **Previous Item(上一條目):[Item 27: Eliminate unchecked warnings(消除 unchecked 警告)](/Chapter-5/Chapter-5-Item-27-Eliminate-unchecked-warnings.md)**
- **Next Item(下一條目):[Item 29: Favor generic types(優先使用泛型)](/Chapter-5/Chapter-5-Item-29-Favor-generic-types.md)**
- Chapter 2. Creating and Destroying Objects(創建和銷毀對象)
- Item 1: Consider static factory methods instead of constructors(考慮以靜態工廠方法代替構造函數)
- Item 2: Consider a builder when faced with many constructor parameters(在面對多個構造函數參數時,請考慮構建器)
- Item 3: Enforce the singleton property with a private constructor or an enum type(使用私有構造函數或枚舉類型實施單例屬性)
- Item 4: Enforce noninstantiability with a private constructor(用私有構造函數實施不可實例化)
- Item 5: Prefer dependency injection to hardwiring resources(依賴注入優于硬連接資源)
- Item 6: Avoid creating unnecessary objects(避免創建不必要的對象)
- Item 7: Eliminate obsolete object references(排除過時的對象引用)
- Item 8: Avoid finalizers and cleaners(避免使用終結器和清除器)
- Item 9: Prefer try with resources to try finally(使用 try-with-resources 優于 try-finally)
- Chapter 3. Methods Common to All Objects(對象的通用方法)
- Item 10: Obey the general contract when overriding equals(覆蓋 equals 方法時應遵守的約定)
- Item 11: Always override hashCode when you override equals(當覆蓋 equals 方法時,總要覆蓋 hashCode 方法)
- Item 12: Always override toString(始終覆蓋 toString 方法)
- Item 13: Override clone judiciously(明智地覆蓋 clone 方法)
- Item 14: Consider implementing Comparable(考慮實現 Comparable 接口)
- Chapter 4. Classes and Interfaces(類和接口)
- Item 15: Minimize the accessibility of classes and members(盡量減少類和成員的可訪問性)
- Item 16: In public classes use accessor methods not public fields(在公共類中,使用訪問器方法,而不是公共字段)
- Item 17: Minimize mutability(減少可變性)
- Item 18: Favor composition over inheritance(優先選擇復合而不是繼承)
- Item 19: Design and document for inheritance or else prohibit it(繼承要設計良好并且具有文檔,否則禁止使用)
- Item 20: Prefer interfaces to abstract classes(接口優于抽象類)
- Item 21: Design interfaces for posterity(為后代設計接口)
- Item 22: Use interfaces only to define types(接口只用于定義類型)
- Item 23: Prefer class hierarchies to tagged classes(類層次結構優于帶標簽的類)
- Item 24: Favor static member classes over nonstatic(靜態成員類優于非靜態成員類)
- Item 25: Limit source files to a single top level class(源文件僅限有單個頂層類)
- Chapter 5. Generics(泛型)
- Item 26: Do not use raw types(不要使用原始類型)
- Item 27: Eliminate unchecked warnings(消除 unchecked 警告)
- Item 28: Prefer lists to arrays(list 優于數組)
- Item 29: Favor generic types(優先使用泛型)
- Item 30: Favor generic methods(優先使用泛型方法)
- Item 31: Use bounded wildcards to increase API flexibility(使用有界通配符增加 API 的靈活性)
- Item 32: Combine generics and varargs judiciously(明智地合用泛型和可變參數)
- Item 33: Consider typesafe heterogeneous containers(考慮類型安全的異構容器)
- Chapter 6. Enums and Annotations(枚舉和注解)
- Item 34: Use enums instead of int constants(用枚舉類型代替 int 常量)
- Item 35: Use instance fields instead of ordinals(使用實例字段替代序數)
- Item 36: Use EnumSet instead of bit fields(用 EnumSet 替代位字段)
- Item 37: Use EnumMap instead of ordinal indexing(使用 EnumMap 替換序數索引)
- Item 38: Emulate extensible enums with interfaces(使用接口模擬可擴展枚舉)
- Item 39: Prefer annotations to naming patterns(注解優于命名模式)
- Item 40: Consistently use the Override annotation(堅持使用 @Override 注解)
- Item 41: Use marker interfaces to define types(使用標記接口定義類型)
- Chapter 7. Lambdas and Streams(λ 表達式和流)
- Item 42: Prefer lambdas to anonymous classes(λ 表達式優于匿名類)
- Item 43: Prefer method references to lambdas(方法引用優于 λ 表達式)
- Item 44: Favor the use of standard functional interfaces(優先使用標準函數式接口)
- Item 45: Use streams judiciously(明智地使用流)
- Item 46: Prefer side effect free functions in streams(在流中使用無副作用的函數)
- Item 47: Prefer Collection to Stream as a return type(優先選擇 Collection 而不是流作為返回類型)
- Item 48: Use caution when making streams parallel(謹慎使用并行流)
- Chapter 8. Methods(方法)
- Item 49: Check parameters for validity(檢查參數的有效性)
- Item 50: Make defensive copies when needed(在需要時制作防御性副本)
- Item 51: Design method signatures carefully(仔細設計方法簽名)
- Item 52: Use overloading judiciously(明智地使用重載)
- Item 53: Use varargs judiciously(明智地使用可變參數)
- Item 54: Return empty collections or arrays, not nulls(返回空集合或數組,而不是 null)
- Item 55: Return optionals judiciously(明智地的返回 Optional)
- Item 56: Write doc comments for all exposed API elements(為所有公開的 API 元素編寫文檔注釋)
- Chapter 9. General Programming(通用程序設計)
- Item 57: Minimize the scope of local variables(將局部變量的作用域最小化)
- Item 58: Prefer for-each loops to traditional for loops(for-each 循環優于傳統的 for 循環)
- Item 59: Know and use the libraries(了解并使用庫)
- Item 60: Avoid float and double if exact answers are required(若需要精確答案就應避免使用 float 和 double 類型)
- Item 61: Prefer primitive types to boxed primitives(基本數據類型優于包裝類)
- Item 62: Avoid strings where other types are more appropriate(其他類型更合適時應避免使用字符串)
- Item 63: Beware the performance of string concatenation(當心字符串連接引起的性能問題)
- Item 64: Refer to objects by their interfaces(通過接口引用對象)
- Item 65: Prefer interfaces to reflection(接口優于反射)
- Item 66: Use native methods judiciously(明智地使用本地方法)
- Item 67: Optimize judiciously(明智地進行優化)
- Item 68: Adhere to generally accepted naming conventions(遵守被廣泛認可的命名約定)
- Chapter 10. Exceptions(異常)
- Item 69: Use exceptions only for exceptional conditions(僅在確有異常條件下使用異常)
- Item 70: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors(對可恢復情況使用 checked 異常,對編程錯誤使用運行時異常)
- Item 71: Avoid unnecessary use of checked exceptions(避免不必要地使用 checked 異常)
- Item 72: Favor the use of standard exceptions(鼓勵復用標準異常)
- Item 73: Throw exceptions appropriate to the abstraction(拋出能用抽象解釋的異常)
- Item 74: Document all exceptions thrown by each method(為每個方法記錄會拋出的所有異常)
- Item 75: Include failure capture information in detail messages(異常詳細消息中應包含捕獲失敗的信息)
- Item 76: Strive for failure atomicity(盡力保證故障原子性)
- Item 77: Don’t ignore exceptions(不要忽略異常)
- Chapter 11. Concurrency(并發)
- Item 78: Synchronize access to shared mutable data(對共享可變數據的同步訪問)
- Item 79: Avoid excessive synchronization(避免過度同步)
- Item 80: Prefer executors, tasks, and streams to threads(Executor、task、流優于直接使用線程)
- Item 81: Prefer concurrency utilities to wait and notify(并發實用工具優于 wait 和 notify)
- Item 82: Document thread safety(文檔應包含線程安全屬性)
- Item 83: Use lazy initialization judiciously(明智地使用延遲初始化)
- Item 84: Don’t depend on the thread scheduler(不要依賴線程調度器)
- Chapter 12. Serialization(序列化)
- Item 85: Prefer alternatives to Java serialization(優先選擇 Java 序列化的替代方案)
- Item 86: Implement Serializable with great caution(非常謹慎地實現 Serializable)
- Item 87: Consider using a custom serialized form(考慮使用自定義序列化形式)
- Item 88: Write readObject methods defensively(防御性地編寫 readObject 方法)
- Item 89: For instance control, prefer enum types to readResolve(對于實例控制,枚舉類型優于 readResolve)
- Item 90: Consider serialization proxies instead of serialized instances(考慮以序列化代理代替序列化實例)