## Chapter 5. Generics(泛型)
### Item 29: Favor generic types(優先使用泛型)
It is generally not too difficult to parameterize your declarations and make use of the generic types and methods provided by the JDK. Writing your own generic types is a bit more difficult, but it’s worth the effort to learn how.
通常,對聲明進行參數化并使用 JDK 提供的泛型和方法并不太難。編寫自己的泛型有點困難,但是值得努力學習。
Consider the simple (toy) stack implementation from Item 7:
考慮 [Item-7](/Chapter-2/Chapter-2-Item-7-Eliminate-obsolete-object-references.md) 中簡單的堆棧實現:
```
// Object-based collection - a prime candidate for generics
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
public boolean isEmpty() {
return size == 0;
}
private void ensureCapacity() {
if (elements.length == size)
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}
```
This class should have been parameterized to begin with, but since it wasn’t, we can generify it after the fact. In other words, we can parameterize it without harming clients of the original non-parameterized version. As it stands, the client has to cast objects that are popped off the stack, and those casts might fail at runtime. The first step in generifying a class is to add one or more type parameters to its declaration. In this case there is one type parameter, representing the element type of the stack, and the conventional name for this type parameter is E (Item 68).
這個類一開始就應該是參數化的,但是因為它不是參數化的,所以我們可以在事后對它進行泛化。換句話說,我們可以對它進行參數化,而不會損害原始非參數化版本的客戶端。按照目前的情況,客戶端必須轉換從堆棧中彈出的對象,而這些轉換可能在運行時失敗。生成類的第一步是向其聲明中添加一個或多個類型參數。在這種情況下,有一個類型參數,表示堆棧的元素類型,這個類型參數的常規名稱是 E([Item-68](/Chapter-9/Chapter-9-Item-68-Adhere-to-generally-accepted-naming-conventions.md))。
The next step is to replace all the uses of the type Object with the appropriate type parameter and then try to compile the resulting program:
下一步是用適當的類型參數替換所有的 Object 類型,然后嘗試編譯修改后的程序:
```
// Initial attempt to generify Stack - won't compile!
public class Stack<E> {
private E[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
elements = new E[DEFAULT_INITIAL_CAPACITY];
}
public void push(E e) {
ensureCapacity();
elements[size++] = e;
}
public E pop() {
if (size == 0)
throw new EmptyStackException();
E result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
} ... // no changes in isEmpty or ensureCapacity
}
```
You’ll generally get at least one error or warning, and this class is no exception. Luckily, this class generates only one error:
通常至少會得到一個錯誤或警告,這個類也不例外。幸運的是,這個類只生成一個錯誤:
```
Stack.java:8: generic array creation
elements = new E[DEFAULT_INITIAL_CAPACITY];
^
```
As explained in Item 28, you can’t create an array of a non-reifiable type, such as E. This problem arises every time you write a generic type that is backed by an array. There are two reasonable ways to solve it. The first solution directly circumvents the prohibition on generic array creation: create an array of Object and cast it to the generic array type. Now in place of an error, the compiler will emit a warning. This usage is legal, but it’s not (in general) typesafe:
正如 [Item-28](/Chapter-5/Chapter-5-Item-28-Prefer-lists-to-arrays.md) 中所解釋的,你不能創建非具體化類型的數組,例如 E。每當你編寫由數組支持的泛型時,就會出現這個問題。有兩種合理的方法來解決它。第一個解決方案直接繞過了創建泛型數組的禁令:創建對象數組并將其強制轉換為泛型數組類型。現在,編譯器將發出一個警告來代替錯誤。這種用法是合法的,但(一般而言)它不是類型安全的:
```
Stack.java:8: warning: [unchecked] unchecked cast
found: Object[], required: E[]
elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY];
^
```
The compiler may not be able to prove that your program is typesafe, but you can. You must convince yourself that the unchecked cast will not compromise the type safety of the program. The array in question (elements) is stored in a private field and never returned to the client or passed to any other method. The only elements stored in the array are those passed to the push method, which are of type E, so the unchecked cast can do no harm.
編譯器可能無法證明你的程序是類型安全的,但你可以。你必須說服自己,unchecked 的轉換不會損害程序的類型安全性。所涉及的數組(元素)存儲在私有字段中,從未返回給客戶端或傳遞給任何其他方法。數組中存儲的惟一元素是傳遞給 push 方法的元素,它們屬于 E 類型,因此 unchecked 的轉換不會造成任何損害。
Once you’ve proved that an unchecked cast is safe, suppress the warning in as narrow a scope as possible (Item 27). In this case, the constructor contains only the unchecked array creation, so it’s appropriate to suppress the warning in the entire constructor. With the addition of an annotation to do this, Stack compiles cleanly, and you can use it without explicit casts or fear of a ClassCastException:
一旦你證明了 unchecked 的轉換是安全的,就將警告限制在盡可能小的范圍內([Item-27](/Chapter-5/Chapter-5-Item-27-Eliminate-unchecked-warnings.md))。在這種情況下,構造函數只包含 unchecked 的數組創建,因此在整個構造函數中取消警告是合適的。通過添加注解來實現這一點,Stack 可以干凈地編譯,而且你可以使用它而無需顯式強制轉換或擔心 ClassCastException:
```
// The elements array will contain only E instances from push(E).
// This is sufficient to ensure type safety, but the runtime
// type of the array won't be E[]; it will always be Object[]!
@SuppressWarnings("unchecked")
public Stack() {
elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY];
}
```
The second way to eliminate the generic array creation error in Stack is to change the type of the field elements from E[] to Object[]. If you do this, you’ll get a different error:
消除 Stack 中泛型數組創建錯誤的第二種方法是將字段元素的類型從 E[] 更改為 Object[]。如果你這樣做,你會得到一個不同的錯誤:
```
Stack.java:19: incompatible types
found: Object, required: E
E result = elements[--size];
^
```
You can change this error into a warning by casting the element retrieved from the array to E, but you will get a warning:
通過將從數組中檢索到的元素轉換為 E,可以將此錯誤轉換為警告,但你將得到警告:
```
Stack.java:19: warning: [unchecked] unchecked cast
found: Object, required: E
E result = (E) elements[--size];
^
```
Because E is a non-reifiable type, there’s no way the compiler can check the cast at runtime. Again, you can easily prove to yourself that the unchecked cast is safe, so it’s appropriate to suppress the warning. In line with the advice of Item 27, we suppress the warning only on the assignment that contains the unchecked cast, not on the entire pop method:
因為 E 是不可具體化的類型,編譯器無法在運行時檢查強制轉換。同樣,你可以很容易地向自己證明 unchecked 的強制轉換是安全的,因此可以適當地抑制警告。根據 [Item-27](/Chapter-5/Chapter-5-Item-27-Eliminate-unchecked-warnings.md) 的建議,我們僅對包含 unchecked 強制轉換的賦值禁用警告,而不是對整個 pop 方法禁用警告:
```
// Appropriate suppression of unchecked warning
public E pop() {
if (size == 0)
throw new EmptyStackException();
// push requires elements to be of type E, so cast is correct
@SuppressWarnings("unchecked")
E result =(E) elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
```
Both techniques for eliminating the generic array creation have their adherents. The first is more readable: the array is declared to be of type E[], clearly indicating that it contains only E instances. It is also more concise: in a typical generic class, you read from the array at many points in the code; the first technique requires only a single cast (where the array is created), while the second requires a separate cast each time an array element is read. Thus, the first technique is preferable and more commonly used in practice. It does, however, cause heap pollution (Item 32): the runtime type of the array does not match its compile-time type (unless E happens to be Object). This makes some programmers sufficiently queasy that they opt for the second technique, though the heap pollution is harmless in this situation.
消除泛型數組創建的兩種技術都有其追隨者。第一個更容易讀:數組聲明為 E[] 類型,這清楚地表明它只包含 E 的實例。它也更簡潔:在一個典型的泛型類中,從數組中讀取代碼中的許多點;第一種技術只需要一次轉換(在創建數組的地方),而第二種技術在每次讀取數組元素時都需要單獨的轉換。因此,第一種技術是可取的,在實踐中更常用。但是,它確實會造成堆污染([Item-32](/Chapter-5/Chapter-5-Item-32-Combine-generics-and-varargs-judiciously.md)):數組的運行時類型與其編譯時類型不匹配(除非 E 恰好是 Object)。盡管堆污染在這種情況下是無害的,但這使得一些程序員感到非常不安,因此他們選擇了第二種技術。
The following program demonstrates the use of our generic Stack class. The program prints its command line arguments in reverse order and converted to uppercase. No explicit cast is necessary to invoke String’s toUpperCase method on the elements popped from the stack, and the automatically generated cast is guaranteed to succeed:
下面的程序演示了通用 Stack 的使用。程序以相反的順序打印它的命令行參數并轉換為大寫。在從堆棧彈出的元素上調用 String 的 toUpperCase 方法不需要顯式轉換,自動生成的轉換保證成功:
```
// Little program to exercise our generic Stack
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
for (String arg : args)
stack.push(arg);
while (!stack.isEmpty())
System.out.println(stack.pop().toUpperCase());
}
```
The foregoing example may appear to contradict Item 28, which encourages the use of lists in preference to arrays. It is not always possible or desirable to use lists inside your generic types. Java doesn’t support lists natively, so some generic types, such as ArrayList, must be implemented atop arrays. Other generic types, such as HashMap, are implemented atop arrays for performance. The great majority of generic types are like our Stack example in that their type parameters have no restrictions: you can create a Stack<Object>, Stack<int[]>, Stack<List<String>>, or Stack of any other object reference type. Note that you can’t create a Stack of a primitive type: trying to create a Stack<int> or Stack<double> will result in a compile-time error.
前面的例子可能與 [Item-28](/Chapter-5/Chapter-5-Item-28-Prefer-lists-to-arrays.md) 相矛盾,Item-28 鼓勵優先使用列表而不是數組。在泛型中使用列表并不總是可能的或可取的。Java 本身不支持列表,因此一些泛型(如 ArrayList)必須在數組之上實現。其他泛型(如 HashMap)是在數組之上實現的,以提高性能。大多數泛型與我們的 Stack 示例相似,因為它們的類型參數沒有限制:你可以創建 `Stack<Object>`、Stack<int[]>、Stack<List<String>> 或任何其他對象引用類型的堆棧。注意,不能創建基本類型的 Stack:試圖創建 `Stack<int>` 或 `Stack<double>` 將導致編譯時錯誤。
This is a fundamental limitation of Java’s generic type system. You can work around this restriction by using boxed primitive types (Item 61). There are some generic types that restrict the permissible values of their type parameters. For example, consider java.util.concurrent.DelayQueue, whose declaration looks like this:
這是 Java 泛型系統的一個基本限制。你可以通過使用裝箱的基本類型([Item-61](/Chapter-9/Chapter-9-Item-61-Prefer-primitive-types-to-boxed-primitives.md))來繞過這一限制。有一些泛型限制了其類型參數的允許值。例如,考慮 java.util.concurrent.DelayQueue,其聲明如下:
```
class DelayQueue<E extends Delayed> implements BlockingQueue<E>
```
The type parameter list (<E extends Delayed>) requires that the actual type parameter E be a subtype of java.util.concurrent.Delayed. This allows the DelayQueue implementation and its clients to take advantage of Delayed methods on the elements of a DelayQueue, without the need for explicit casting or the risk of a ClassCastException. The type parameter E is known as a bounded type parameter. Note that the subtype relation is defined so that every type is a subtype of itself [JLS, 4.10], so it is legal to create a DelayQueue<Delayed>.
類型參數列表(<E extends Delayed>)要求實際的類型參數 E 是 java.util.concurrent.Delayed 的一個子類型。這允許 DelayQueue 實現及其客戶端利用 DelayQueue 元素上的 Delayed 方法,而不需要顯式轉換或 ClassCastException 的風險。類型參數 E 稱為有界類型參數。注意,子類型關系的定義使得每個類型都是它自己的子類型 [JLS, 4.10],所以創建 `DelayQueue<Delayed>` 是合法的。
In summary, generic types are safer and easier to use than types that require casts in client code. When you design new types, make sure that they can be used without such casts. This will often mean making the types generic. If you have any existing types that should be generic but aren’t, generify them. This will make life easier for new users of these types without breaking existing clients (Item 26).
總之,泛型比需要在客戶端代碼中轉換的類型更安全、更容易使用。在設計新類型時,請確保可以在不使用此類類型轉換的情況下使用它們。這通常意味著使類型具有通用性。如果你有任何應該是泛型但不是泛型的現有類型,請對它們進行泛型。這將使這些類型的新用戶在不破壞現有客戶端([Item-26](/Chapter-5/Chapter-5-Item-26-Do-not-use-raw-types.md))的情況下更容易使用。
---
**[Back to contents of the chapter(返回章節目錄)](/Chapter-5/Chapter-5-Introduction.md)**
- **Previous Item(上一條目):[Item 28: Prefer lists to arrays(list 優于數組)](/Chapter-5/Chapter-5-Item-28-Prefer-lists-to-arrays.md)**
- **Next Item(下一條目):[Item 30: Favor generic methods(優先使用泛型方法)](/Chapter-5/Chapter-5-Item-30-Favor-generic-methods.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(考慮以序列化代理代替序列化實例)