I am studying Java Generics using the book "Introduction to Java Programming and Data Structures" by Y. Daniel Liang, and I don't understand one of the exercises:
"19.3 (Pair of objects of the same type) Create a Pair class that encapsulates two objects of the same data type in an instance of Pair.
19.4 (Using wildcards) Write a generic static method that returns the smallest value in an instance of Pair from Programming Exercise 19.3."
The solution code is as follows:
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));*/
}
}
}
My problem is with the method declaration public static <T extends Comparable<? super T>> T smallest(Pair<T> p)
I understand that in order to compare the objects T within an instance of Pair, T must be an instance of Comparable and therefore you have to declare <T extends Comparable>
. However I don't understand the <? super T>
part thereafter. Can somebody explain this to me? Thanks in advance!