5.3.泛类的创建

\(5.3\)泛类的创建

1.泛型方法的创建

1
2
3
4
5
6
7
8
public static <K,V> V get(Map61B<K,V> map, K key) {
if map.containsKey(key) {
return map.get(key);
}
return null;
}
//why <K,V>?because the parameters takes two different
//genetic types,so we alse use two.

2.>运算符的泛型化

1
2
public static <K extends Comparable<K>, V> K maxKey(Map61B<K, V> map) {...}
// the "extends" assure that the object has a "compareTo" method.

  此处的\(extends\)关键词,可以理解为“\(K\)必须是可比的”的声明。\(extends\)会对对象施加一个约束、而非赋予它新的能力。