文章

Generics

Generic Methods

例子

1
2
3
4
5
6
public static <K,V> V get(Map61B<K,V> map, K key) {
    if map.containsKey(key) {
        return map.get(key);
    }
    return null;
}

在type未知的情况下引用Comparable,下面的example似乎不太行得通 毕竟Not all objects have a compareTo method!

1
2
3
4
5
6
7
8
9
10
public static <K, V> K maxKey(Map61B<K, V> map) {
    List<K> keylist = map.keys();
    K largest = map.get(0);
    for (K k: keylist) {
        if (k > largest) {
            largest = k;
        }
    }
    return largest;
}

接下来是改进版本

1
public static <K extends Comparable<K>, V> K maxKey(Map61B<K, V> map) {...}

Type upper bounds

why does it “extend” comparable and not “implement”?

Well, it turns out, “extends” in this context has a different meaning than in the polymorphism context.

This different use of extends is called type upper bounding. Confusing? That’s okay, it is confusing. Just remember, in the context of inheritance, the extends keyword is active in giving the subclass the abilities of the superclass. You can think of it as a fairy Godmother: she sees your needs and helps you out with some of her fairy magic. On the other hand, in the context of generics, extends simply states a fact: You must be a subclass of whatever you’re extending.

When used with generics (like in generic method headers), extends imposes a constraint rather than grants new abilities.

Summary

We’ve seen four new features of Java that make generics more powerful:

  • Autoboxing and auto-unboxing of primitive wrapper types.
  • Promotion/widening between primitive types.
  • Specification of generic types for methods (before return type).
  • Type upper bounds in generic methods (e.g. K extends Comparable<K>).
本文由作者按照 CC BY 4.0 进行授权