2020/08/24

[筆記] Effective Java #30 優先考慮泛型方法

Effective Java 3rd 簡體中文版筆記 #30 優先考慮泛型方法
Class 可以使用泛型,當然方法也可以,在靜態工具方法常會這樣使用。像是 java.util.Collections 中,大部分的方法都有泛型化。將方法泛型化時,先定義 <E> 作為泛型的類型參數 (type parameter),後續就可以使用 E 來代替。
public static <E> Set<E> union(Set<E> s1, Set<E> s2) {
    Set<E> result = new HashSet<>(s1);
    result.addAll(s2);
    return result;
}
要撰寫一個恆等函數 (identify function),若每個 class 都提供一個恆等函數,這樣就會有許多只有類型不同其它都相同的程式碼,這一類的方法就適合將其獨立出來,建立成 generic singleton factory,Collections.emptySet() 就是一個例子。
@SuppressWarnings("unchecked")
public static final <T> Set<T> emptySet() {
    return (Set<T>) EMPTY_SET;
}
另一種比較少見的是遞迴類型限制 (recursive type bound) 的使用,最普遍的用法是在 Comparable 上,像是下面方法宣告的是 public static <E extends Comparable<E>> E max(Collection<E> c),可以解釋為 E 是本身有實作 Comparable,可以自己與自己作比較的。
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;
}
泛型方法就像泛型 class 一樣,應確保在調用上不需要作類型的轉換,對客戶來說,泛型的使用應該是輕鬆的,不會破壞已存在的程式碼。

轉載請註明原文網址 https://cookieandcoketw.blogspot.com/2020/08/effective-java-30-generic-method.html

沒有留言:

張貼留言