## Chapter 5. Generics(泛型)
### Item 30: Favor generic methods(優先使用泛型方法)
Just as classes can be generic, so can methods. Static utility methods that operate on parameterized types are usually generic. All of the “algorithm” methods in Collections (such as binarySearch and sort) are generic.
類可以是泛型的,方法也可以是泛型的。操作參數化類型的靜態實用程序方法通常是泛型的。Collections 類中的所有「算法」方法(如 binarySearch 和 sort)都是泛型的。
Writing generic methods is similar to writing generic types. Consider this deficient method, which returns the union of two sets:
編寫泛型方法類似于編寫泛型類型。考慮這個有缺陷的方法,它返回兩個集合的并集:
```
// Uses raw types - unacceptable! (Item 26)
public static Set union(Set s1, Set s2) {
Set result = new HashSet(s1);
result.addAll(s2);
return result;
}
```
This method compiles but with two warnings:
該方法可進行編譯,但有兩個警告:
```
Union.java:5: warning: [unchecked] unchecked call to
HashSet(Collection<? extends E>) as a member of raw type HashSet
Set result = new HashSet(s1);
^
Union.java:6: warning: [
unchecked] unchecked call to
addAll(Collection<? extends E>) as a member of raw type Set
result.addAll(s2);
^
```
To fix these warnings and make the method typesafe, modify its declaration to declare a type parameter representing the element type for the three sets (the two arguments and the return value) and use this type parameter throughout the method. **The type parameter list, which declares the type parameters, goes between a method’s modifiers and its return type.** In this example, the type parameter list is `<E>`, and the return type is `Set<E>`. The naming conventions for type parameters are the same for generic methods and generic types (Items 29, 68):
要修復這些警告并使方法類型安全,請修改其聲明,以聲明表示三個集合(兩個參數和返回值)的元素類型的類型參數,并在整個方法中使用該類型參數。類型參數列表聲明類型參數,它位于方法的修飾符與其返回類型之間。在本例中,類型參數列表為 `<E>`,返回類型為 `Set<E>`。類型參數的命名約定與泛型方法和泛型類型的命名約定相同([Item-29](/Chapter-5/Chapter-5-Item-29-Favor-generic-types.md)、[Item-68](/Chapter-9/Chapter-9-Item-68-Adhere-to-generally-accepted-naming-conventions.md)):
```
// Generic method
public static <E> Set<E> union(Set<E> s1, Set<E> s2) {
Set<E> result = new HashSet<>(s1);
result.addAll(s2);
return result;
}
```
At least for simple generic methods, that’s all there is to it. This method compiles without generating any warnings and provides type safety as well as ease of use. Here’s a simple program to exercise the method. This program contains no casts and compiles without errors or warnings:
至少對于簡單的泛型方法,這就是(要注意細節的)全部。該方法編譯時不生成任何警告,并且提供了類型安全性和易用性。這里有一個簡單的程序來演示。這個程序不包含轉換,編譯時沒有錯誤或警告:
```
// Simple program to exercise generic method
public static void main(String[] args) {
Set<String> guys = Set.of("Tom", "Dick", "Harry");
Set<String> stooges = Set.of("Larry", "Moe", "Curly");
Set<String> aflCio = union(guys, stooges);
System.out.println(aflCio);
}
```
When you run the program, it prints [Moe, Tom, Harry, Larry, Curly, Dick]. (The order of the elements in the output is implementation-dependent.)
當你運行程序時,它會打印出 [Moe, Tom, Harry, Larry, Curly, Dick]。(輸出元素的順序可能不同)。
A limitation of the union method is that the types of all three sets (both input parameters and the return value) have to be exactly the same. You can make the method more flexible by using bounded wildcard types (Item 31).
union 方法的一個限制是,所有三個集合(輸入參數和返回值)的類型必須完全相同。你可以通過使用有界通配符類型([Item-31](/Chapter-5/Chapter-5-Item-31-Use-bounded-wildcards-to-increase-API-flexibility.md))使方法更加靈活。
On occasion, you will need to create an object that is immutable but applicable to many different types. Because generics are implemented by erasure (Item 28), you can use a single object for all required type parameterizations, but you need to write a static factory method to repeatedly dole out the object for each requested type parameterization. This pattern, called the generic singleton factory, is used for function objects (Item 42) such as Collections.reverseOrder, and occasionally for collections such as Collections.emptySet.
有時,你需要創建一個對象,該對象是不可變的,但適用于許多不同類型。因為泛型是由擦除([Item-28](/Chapter-5/Chapter-5-Item-28-Prefer-lists-to-arrays.md))實現的,所以你可以為所有需要的類型參數化使用單個對象,但是你需要編寫一個靜態工廠方法,為每個請求的類型參數化重復分配對象。這種模式稱為泛型單例工廠,可用于函數對象([Item-42](/Chapter-7/Chapter-7-Item-42-Prefer-lambdas-to-anonymous-classes.md)),如 Collections.reverseOrder,偶爾也用于集合,如 Collections.emptySet。
Suppose that you want to write an identity function dispenser. The libraries provide Function.identity, so there’s no reason to write your own (Item 59), but it is instructive. It would be wasteful to create a new identity function object time one is requested, because it’s stateless. If Java’s generics were reified, you would need one identity function per type, but since they’re erased a generic singleton will suffice. Here’s how it looks:
假設你想要編寫一個恒等函數分發器。這些庫提供 Function.identity,所以沒有理由編寫自己的庫([Item-59](/Chapter-9/Chapter-9-Item-59-Know-and-use-the-libraries.md)),但是它很有指導意義。在請求標識函數對象時創建一個新的標識函數對象是浪費時間的,因為它是無狀態的。如果 Java 的泛型被具體化了,那么每個類型都需要一個標識函數,但是由于它們已經被擦除,一個泛型單例就足夠了。它是這樣的:
```
// Generic singleton factory pattern
private static UnaryOperator<Object> IDENTITY_FN = (t) -> t;
@SuppressWarnings("unchecked")
public static <T> UnaryOperator<T> identityFunction() {
return (UnaryOperator<T>) IDENTITY_FN;
}
```
The cast of IDENTITY_FN to (`UnaryFunction<T>`) generates an unchecked cast warning, as `UnaryOperator<Object>` is not a `UnaryOperator<T>` for every T. But the identity function is special: it returns its argument unmodified, so we know that it is typesafe to use it as a `UnaryFunction<T>`, whatever the value of T. Therefore, we can confidently suppress the unchecked cast warning generated by this cast. Once we’ve done this, the code compiles without error or warning.
IDENTITY_FN 到(`UnaryFunction<T>`)的轉換會生成一個 unchecked 轉換警告,因為 `UnaryOperator<Object>` 并不是每個 T 都是 `UnaryOperator<T>`,但是恒等函數是特殊的:它會返回未修改的參數,所以我們知道,無論 T 的值是多少,都可以將其作為 `UnaryFunction<T>` 使用,這是類型安全的。一旦我們這樣做了,代碼編譯就不會出現錯誤或警告。
Here is a sample program that uses our generic singleton as a `UnaryOperator<String>` and a `UnaryOperator<Number>`. As usual, it contains no casts and compiles without errors or warnings:
下面是一個示例程序,它使用我們的泛型單例作為 `UnaryOperator<String>` 和 `UnaryOperator<Number>`。像往常一樣,它不包含類型轉換和編譯,沒有錯誤或警告:
```
// Sample program to exercise generic singleton
public static void main(String[] args) {
String[] strings = { "jute", "hemp", "nylon" };
UnaryOperator<String> sameString = identityFunction();
for (String s : strings)
System.out.println(sameString.apply(s));
Number[] numbers = { 1, 2.0, 3L };
UnaryOperator<Number> sameNumber = identityFunction();
for (Number n : numbers)
System.out.println(sameNumber.apply(n));
}
```
It is permissible, though relatively rare, for a type parameter to be bounded by some expression involving that type parameter itself. This is what’s known as a recursive type bound. A common use of recursive type bounds is in connection with the Comparable interface, which defines a type’s natural ordering (Item 14). This interface is shown here:
允許類型參數被包含該類型參數本身的表達式限制,盡管這種情況比較少見。這就是所謂的遞歸類型限定。遞歸類型邊界的一個常見用法是與 Comparable 接口相關聯,后者定義了類型的自然順序([Item-14](/Chapter-3/Chapter-3-Item-14-Consider-implementing-Comparable.md))。該界面如下圖所示:
```
public interface Comparable<T> {
int compareTo(T o);
}
```
The type parameter T defines the type to which elements of the type implementing `Comparable<T>` can be compared. In practice, nearly all types can be compared only to elements of their own type. So, for example, String implements `Comparable<String>`, Integer implements `Comparable<Integer>`, and so on.
類型參數 T 定義了實現 `Comparable<T>` 的類型的元素可以與之進行比較的類型。在實踐中,幾乎所有類型都只能與它們自己類型的元素進行比較。例如,String 實現 `Comparable<String>`, Integer 實現 `Comparable<Integer>`,等等。
Many methods take a collection of elements implementing Comparable to sort it, search within it, calculate its minimum or maximum, and the like. To do these things, it is required that every element in the collection be comparable to every other element in it, in other words, that the elements of the list be mutually comparable. Here is how to express that constraint:
許多方法采用實現 Comparable 的元素集合,在其中進行搜索,計算其最小值或最大值,等等。要做到這些,需要集合中的每個元素與集合中的每個其他元素相比較,換句話說,就是列表中的元素相互比較。下面是如何表達這種約束(的示例):
```
// Using a recursive type bound to express mutual comparability
public static <E extends Comparable<E>> E max(Collection<E> c);
```
The type bound `<E extends Comparable<E>>` may be read as “any type E that can be compared to itself,” which corresponds more or less precisely to the notion of mutual comparability.
類型限定 `<E extends Comparable<E>>` 可以被理解為「可以與自身進行比較的任何類型 E」,這或多或少與相互可比性的概念相對應。
Here is a method to go with the previous declaration. It calculates the maximum value in a collection according to its elements’ natural order, and it compiles without errors or warnings:
下面是一個與前面聲明相同的方法。它根據元素的自然順序計算集合中的最大值,編譯時沒有錯誤或警告:
```
// Returns max value in a collection - uses recursive type bound
public static <E extends Comparable<E>> E max(Collection<E> c) {
if (c.isEmpty())
throw new IllegalArgumentException("Empty collection");
E result = null;
for (E e : c)
if (result == null || e.compareTo(result) > 0)
result = Objects.requireNonNull(e);
return result;
}
```
Note that this method throws IllegalArgumentException if the list is empty. A better alternative would be to return an `Optional<E>` (Item 55).
注意,如果列表為空,該方法將拋出 IllegalArgumentException。更好的選擇是返回一個 `Optional<E>`([Item-55](/Chapter-8/Chapter-8-Item-55-Return-optionals-judiciously.md))。
Recursive type bounds can get much more complex, but luckily they rarely do. If you understand this idiom, its wildcard variant (Item 31), and the simulated self-type idiom (Item 2), you’ll be able to deal with most of the recursive type bounds you encounter in practice.
遞歸類型限定可能會變得復雜得多,但幸運的是,這種情況很少。如果你理解這個習慣用法、它的通配符變量([Item-31](/Chapter-5/Chapter-5-Item-31-Use-bounded-wildcards-to-increase-API-flexibility.md))和模擬的自類型習慣用法([Item-2](/Chapter-2/Chapter-2-Item-2-Consider-a-builder-when-faced-with-many-constructor-parameters.md)),你就能夠處理在實踐中遇到的大多數遞歸類型限定。
In summary, generic methods, like generic types, are safer and easier to use than methods requiring their clients to put explicit casts on input parameters and return values. Like types, you should make sure that your methods can be used without casts, which often means making them generic. And like types, you should generify existing methods whose use requires casts. This makes life easier for new users 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 29: Favor generic types(優先使用泛型)](/Chapter-5/Chapter-5-Item-29-Favor-generic-types.md)**
- **Next Item(下一條目):[Item 31: Use bounded wildcards to increase API flexibility(使用有界通配符增加 API 的靈活性)](/Chapter-5/Chapter-5-Item-31-Use-bounded-wildcards-to-increase-API-flexibility.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(考慮以序列化代理代替序列化實例)