What and Why
There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.
How
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound.
注意: In this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces)
public class Box<T> {
private T t;
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
public <U extends Number> void inspect(U u){
System.out.println("T: " + t.getClass().getName());
System.out.println("U: " + u.getClass().getName());
}
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
integerBox.set(new Integer(10));
integerBox.inspect("some text"); // error: this is still String!
}
}
In addition to limiting the types you can use to instantiate a generic type, bounded type parameters allow you to invoke methods defined in the bounds:
public class NaturalNumber<T extends Integer> {
private T n;
public NaturalNumber(T n) { this.n = n; }
public boolean isEven() {
return n.intValue() % 2 == 0;
}
// ...
}
上面的例子中日丹,由于限定了T是Integer的子類哲虾,所以n可以直接調(diào)用Integer中的方法intValue齐帚。
Multiple Bounds
如果有多個限定对妄,寫法如下:
<T extends B1 & B2 & B3>
假設(shè)有3個限定A, B摩瞎, C旗们,其中A是一個類构灸,B和C都是接口:
Class A { /* ... */ }
interface B { /* ... */ }
interface C { /* ... */ }
那么應(yīng)該把A放在最前面喜颁,否則會報錯:
class D <T extends A & B & C> { /* ... */ }
class D <T extends B & A & C> { /* ... */ } // compile-time error
Generic Methods and Bounded Type Parameters
假設(shè)我們要實現(xiàn)以下代碼的功能:
public static <T> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e > elem) // compiler error
++count;
return count;
}
但是這段代碼會出現(xiàn)編譯錯誤半开,因為T的具體類型是未知的,不能直接通過e > elem
判斷大猩菝住(只有數(shù)值類型才能直接這樣判斷)鬓长。這個時候我們可以使用Bounded Type Parameters來很好的解決這個問題:
public interface Comparable<T> {
public int compareTo(T o);
}
public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e.compareTo(elem) > 0)
++count;
return count;
}
我們限定T必須實現(xiàn)Comparable<T>接口痢士,而Comparable<T>接口中定義了比較兩個T的大小的方法。