Section 8.12. Case Study: The sort( ) Method

8.12. Case Study: The sort( ) Method

Poking around in the java.util.Collections class we find all kinds of static utility methods for working with collections. Among them is this goodythe static generic method sort( ):

     <T extends Comparable<? super T>> void sort( List<T> list ) { ... }

Another nut for us to crack. Let's focus on the last part of the bound:

     Comparable<? super T>

This is a wildcard instantiation of the Comparable interface, so we can read the extends as implements, if it helps. Comparable holds a compareTo( ) method for some parameter type. A Comparable<String> means that the compareTo( ) method takes type String. Therefore, Comparable<? super T> is the set of instantiations of Comparable on T and all of its superclasses. A Comparable<T> suffices and, at the other end, so does a Comparable<Object>. What this means in English is that the elements must be comparable to their own type or some supertype of their own type. This is sufficient to ensure that the elements can all be compared to one another, but not as restrictive as saying that they must all implement the compareTo( ) method themselves. Some of the elements may inherit the Comparable interface from a parent class that knows how to compare only to a supertype of T and that is exactly what is allowed here.

    Learning Java
    Learning Java
    ISBN: 0596008732
    EAN: 2147483647
    Year: 2005
    Pages: 262

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: