Rec 04
Problems
01. Generic Type parameter and static field
static fieldAs we have seen from Lab 03,
A class's generic type parameters cannot be used in
staticmethods orstaticfields.
For more information, please go to Lab 03!
02. Variance Relationship about Generics and Wildcards
Just follow the different rules we have introduced in Lec 06 - Wildcards
03. Type Inference and the Application of Wildcards
If
class A implements Comparable<A>, andclass B extends A, thenBactually implementsComparable<A>notComparable<B>!
The original max method is as follows,
static <T extends Comparable<T>> T max (List<T>, list) {
T max = list.get(0);
if (list.get(1).compareTo(max)) > 0) {
return list.get(1);
}
return max;
}To make the max method more flexible and allow assignments (i) Fruit f = max(apples); and (ii) Apple a = max(apples);, we need to adjust the method header using PECS (Producer-Extends, Consumer-Super) principles. Here's the solution and explanation:
Explanation using PECS
Producer (List<? extends T>)
The List acts as a producer of elements (we read T instances from it). Using ? extends T allows the list to contain subtypes of T. For example:
If
T = Fruit, aList<Apple>(whereApple extends Fruit) is valid.This enables
Fruit f = max(apples);(assignment (i)), whereapplesisList<Apple>.
Consumer (Comparable<? super T>)
The Comparable interface is a consumer (it accepts T as an argument in compareTo). Using ? super T allows T to implement Comparable for itself or any supertype. For example:
If
Appledoesn’t implementComparable<Apple>butFruitimplementsComparable<Fruit>,Applecan still be compared via its supertypeFruit.This enables
Apple a = max(apples);(assignment (ii)), asApplesatisfiesComparable<? super Apple>(viaFruit).
Tips
If
class A implements Comparable<A>, andclass B extends A, thenBactually implementsComparable<A>notComparable<B>!
Last updated