【发布时间】:2021-12-29 19:39:39
【问题描述】:
我正在使用 Y. Daniel Liang 的《Java 编程和数据结构简介》一书学习 Java 泛型,但其中一个练习我不懂:
"19.3(同一类型的对象对)创建一个封装两个对象的Pair类 在 Pair 的实例中具有相同的数据类型。
19.4(使用通配符)编写一个通用静态方法,它返回一个数组中的最小值 编程练习 19.3 中的 Pair 实例。"
解决方案代码如下:
public class Exercise19_04 {
public static class Pair<T> {
public final T one;
public final T two;
public Pair(T one, T two) {
this.one = one;
this.two = two;
}
}
public static class Main {
// To have the smallest between two objects, they need to be comparable.
public static <T extends Comparable<? super T>> T smallest(Pair<T> p) {
if (p.one.compareTo(p.two) < 0) {
return p.one;
} else {
return p.two;
}
}
public static void main(String[] args) {
Pair<Double> pd = new Pair<>(7.0, 6.3);
System.out.println(smallest(pd));
Pair<String> ps = new Pair<>("big", "small");
System.out.println(smallest(ps));
/* Lines below are not compilable because Color is not comparable
Pair<String> pc = new Pair<>(java.awt.Color.BLUE, java.awt.Color.RED);
System.out.println(smallest(ps));*/
}
}
}
我的问题在于方法声明public static <T extends Comparable<? super T>> T smallest(Pair<T> p)
我知道,为了比较 Pair 实例中的对象 T,T 必须是 Comparable 的实例,因此您必须声明 <T extends Comparable>。但是我不明白之后的<? super T> 部分。有人可以向我解释一下吗?提前致谢!
【问题讨论】:
-
致更亲近的选民:OP 显然没有与 PECS 作斗争,也没有具体说明为什么
<? super T>而不仅仅是<T>; op 只是想解释一下为什么 Comparable 甚至有泛型。 -
这些近距离投票怎么没有登记?
-
@RobertHarvey 已登记接近票数,但问题现已重新开放。