Da Linguaggi di programmazione: principi e paradigmi Di Maurizio Gabbrielli, Simone Martini
The bound mechanism for type variables is fairly sophisticated and flexible. In particular, a type variable can appear in its own bound. We restrict ourselves to a single example of this case, and we refer the reader to the bibliography for a deeper discussion.
The elements of a class are comparable if the class implements the
Comparableinterface. We want to define a method which, given a list of elements of generic type as its argument, returns the maximum element of this list. What is the signature we can give to this max method? A first attempt is:public static <T extends Comparable<T>> T max(List<T> list)This expresses the fact that the elements of the list must be comparable with elements of the same type. We now try to use
max. We have a typeFoowhich allows us to compare objects:class Foo implements Comparable<Object>{...} List<Foo> cf = ....;We now invoke
max(cf): each element incf(is aFooand therefore) is comparable with any object, in particular with everyFoo. But the compiler signals an error, becauseFoodoes not implementComparable<Foo>. In reality it is sufficient thatFoois comparable with one of its own supertypes:public static <T extends Comparable<? super T>> T max(List<T> list)Now, under the same conditions as before,
Max(cf)is correct becauseFooimplementsComparable<Object>.
-
Suppongo che
? super Tsignifichi qualsiasi supertipo diT.Poiché
Objectè un supertipo diT, esegue la seguente firma dimaxlavoro?public static <T extends Comparable<Object>> T max(List<T> list)Se sì, perché non usarlo invece l'ultimo nella citazione?
- Questo è un esempio che coinvolge l'interfaccia
Comparable. Qual 'é problema generale che possiamo usare il metodo nella citazione per risolvere?