Item 30: Favor generic methods(優(yōu)先使用泛型方法)

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.

類可以是泛型的,方法也可以是泛型的。操作參數(shù)化類型的靜態(tài)實(shí)用程序方法通常是泛型的。Collections 類中的所有「算法」方法(如 binarySearch 和 sort)都是泛型的。

Writing generic methods is similar to writing generic types. Consider this deficient(adj. 不足的;有缺陷的;不充分的) method, which returns the union of two sets:

編寫泛型方法類似于編寫泛型類型??紤]這個(gè)有缺陷的方法,它返回兩個(gè)集合的并集:

// 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:

該方法可進(jìn)行編譯,但有兩個(gè)警告:

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):

要修復(fù)這些警告并使方法類型安全,請修改其聲明,以聲明表示三個(gè)集合(兩個(gè)參數(shù)和返回值)的元素類型的類型參數(shù),并在整個(gè)方法中使用該類型參數(shù)。類型參數(shù)列表聲明類型參數(shù),它位于方法的修飾符與其返回類型之間。在本例中,類型參數(shù)列表為 <E>,返回類型為 Set<E>。類型參數(shù)的命名約定與泛型方法和泛型類型的命名約定相同(Item-29、Item-68):

// 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:

至少對于簡單的泛型方法,這就是(要注意細(xì)節(jié)的)全部。該方法編譯時(shí)不生成任何警告,并且提供了類型安全性和易用性。這里有一個(gè)簡單的程序來演示。這個(gè)程序不包含轉(zhuǎn)換,編譯時(shí)沒有錯(cuò)誤或警告:

// 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.)

當(dāng)你運(yùn)行程序時(shí),它會(huì)打印出 [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 方法的一個(gè)限制是,所有三個(gè)集合(輸入?yún)?shù)和返回值)的類型必須完全相同。你可以通過使用有界通配符類型(Item-31)使方法更加靈活。

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.

有時(shí),你需要?jiǎng)?chuàng)建一個(gè)對象,該對象是不可變的,但適用于許多不同類型。因?yàn)榉盒褪怯刹脸?a target="_blank" rel="nofollow">Item-28)實(shí)現(xiàn)的,所以你可以為所有需要的類型參數(shù)化使用單個(gè)對象,但是你需要編寫一個(gè)靜態(tài)工廠方法,為每個(gè)請求的類型參數(shù)化重復(fù)分配對象。這種模式稱為泛型單例工廠,可用于函數(shù)對象(Item-42),如 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:

假設(shè)你想要編寫一個(gè)恒等函數(shù)分發(fā)器。這些庫提供 Function.identity,所以沒有理由編寫自己的庫(Item-59),但是它很有指導(dǎo)意義。在請求標(biāo)識函數(shù)對象時(shí)創(chuàng)建一個(gè)新的標(biāo)識函數(shù)對象是浪費(fèi)時(shí)間的,因?yàn)樗菬o狀態(tài)的。如果 Java 的泛型被具體化了,那么每個(gè)類型都需要一個(gè)標(biāo)識函數(shù),但是由于它們已經(jīng)被擦除,一個(gè)泛型單例就足夠了。它是這樣的:

// 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>)的轉(zhuǎn)換會(huì)生成一個(gè) unchecked 轉(zhuǎn)換警告,因?yàn)?UnaryOperator<Object> 并不是每個(gè) T 都是 UnaryOperator<T>,但是恒等函數(shù)是特殊的:它會(huì)返回未修改的參數(shù),所以我們知道,無論 T 的值是多少,都可以將其作為 UnaryFunction<T> 使用,這是類型安全的。一旦我們這樣做了,代碼編譯就不會(huì)出現(xiàn)錯(cuò)誤或警告。

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:

下面是一個(gè)示例程序,它使用我們的泛型單例作為 UnaryOperator<String>UnaryOperator<Number>。像往常一樣,它不包含類型轉(zhuǎn)換和編譯,沒有錯(cuò)誤或警告:

// 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:

允許類型參數(shù)被包含該類型參數(shù)本身的表達(dá)式限制,盡管這種情況比較少見。這就是所謂的遞歸類型限定。遞歸類型邊界的一個(gè)常見用法是與 Comparable 接口相關(guān)聯(lián),后者定義了類型的自然順序(Item-14)。該界面如下圖所示:

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.

類型參數(shù) T 定義了實(shí)現(xiàn) Comparable<T> 的類型的元素可以與之進(jìn)行比較的類型。在實(shí)踐中,幾乎所有類型都只能與它們自己類型的元素進(jìn)行比較。例如,String 實(shí)現(xiàn) Comparable<String>, Integer 實(shí)現(xiàn) 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:

許多方法采用實(shí)現(xiàn) Comparable 的元素集合,在其中進(jìn)行搜索,計(jì)算其最小值或最大值,等等。要做到這些,需要集合中的每個(gè)元素與集合中的每個(gè)其他元素相比較,換句話說,就是列表中的元素相互比較。下面是如何表達(dá)這種約束(的示例):

// 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>> 可以被理解為「可以與自身進(jìn)行比較的任何類型 E」,這或多或少與相互可比性的概念相對應(yīng)。

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:

下面是一個(gè)與前面聲明相同的方法。它根據(jù)元素的自然順序計(jì)算集合中的最大值,編譯時(shí)沒有錯(cuò)誤或警告:

// 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。更好的選擇是返回一個(gè) Optional<E>Item-55)。

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.

遞歸類型限定可能會(huì)變得復(fù)雜得多,但幸運(yùn)的是,這種情況很少。如果你理解這個(gè)習(xí)慣用法、它的通配符變量(Item-31)和模擬的自類型習(xí)慣用法(Item-2),你就能夠處理在實(shí)踐中遇到的大多數(shù)遞歸類型限定。

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).

總之,與要求客戶端對輸入?yún)?shù)和返回值進(jìn)行顯式轉(zhuǎn)換的方法相比,泛型方法與泛型一樣,更安全、更容易使用。與類型一樣,你應(yīng)該確保你的方法可以在不使用類型轉(zhuǎn)換的情況下使用,這通常意味著要使它們具有通用性。與類型類似,你應(yīng)該將需要強(qiáng)制類型轉(zhuǎn)換的現(xiàn)有方法泛型化。這使得新用戶在不破壞現(xiàn)有客戶端的情況下更容易使用(Item-26)。


Back to contents of the chapter(返回章節(jié)目錄)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容