1.
Bounded types are especially useful when you need to ensure that one type parameter is compatible with another. For example, consider the following class called Pair, which stores two objects that must be compatible with each other:
class Pair<T, V extends T> {
T first;
V second;
Pair(T a, V b) {
first = a;
second = b;
}
// This is OK because both T and V are Integer.
Pair<Integer, Integer> x = new Pair<Integer, Integer>(1, 2);
// This is OK because Integer is a subclass of Number.
Pair<Number, Integer> y = new Pair<Number, Integer>(10.4, 12);
However, the following is invalid:
// This causes an error because String is not
// a subclass of Number
Pair<Number, String> z = new Pair<Number, String>(10.4, "12");
2.Bounded Wildcards
In general, to establish an upper bound for a wildcard, use the following type of wildcard
expression:
<? extends superclass>
where superclass is the name of the class that serves as the upper bound. Remember, this is an
inclusive clause because the class forming the upper bound (that is, specified by superclass) is
also within bounds.
You can also specify a lower bound for a wildcard by adding a super clause to a wildcard
declaration. Here is its general form:
<? super subclass>
In this case, only classes that are superclasses of subclass are acceptable arguments. This is an
exclusive clause, because it will not match the class specified by subclass.
Bounded types are especially useful when you need to ensure that one type parameter is compatible with another. For example, consider the following class called Pair, which stores two objects that must be compatible with each other:
class Pair<T, V extends T> {
T first;
V second;
Pair(T a, V b) {
first = a;
second = b;
}
// This is OK because both T and V are Integer.
Pair<Integer, Integer> x = new Pair<Integer, Integer>(1, 2);
// This is OK because Integer is a subclass of Number.
Pair<Number, Integer> y = new Pair<Number, Integer>(10.4, 12);
However, the following is invalid:
// This causes an error because String is not
// a subclass of Number
Pair<Number, String> z = new Pair<Number, String>(10.4, "12");
2.Bounded Wildcards
In general, to establish an upper bound for a wildcard, use the following type of wildcard
expression:
<? extends superclass>
where superclass is the name of the class that serves as the upper bound. Remember, this is an
inclusive clause because the class forming the upper bound (that is, specified by superclass) is
also within bounds.
You can also specify a lower bound for a wildcard by adding a super clause to a wildcard
declaration. Here is its general form:
<? super subclass>
In this case, only classes that are superclasses of subclass are acceptable arguments. This is an
exclusive clause, because it will not match the class specified by subclass.
本文介绍Java泛型中的有界类型参数和通配符的概念。通过实例解释如何定义和使用带有上界和下界的类型参数,确保类型之间的兼容性。
1028

被折叠的 条评论
为什么被折叠?



