Search code examples
javalistgenericscomparableparameterized

How can a custom parameterized list object be created in Java with Comparables?


I am attempting to create a custom list object in Java that is to have parameterized types in "<>" (like ArrayLists). However, these paramaterized types need to implement the Comparable interface (because the list will be automatically sorted and organized).

The problem I am having is with syntax and ensuring that 1) the list elements are Comparable Objects, not just any Objects, and 2) getter methods like get(index) should return Objects of the type for the list without requiring the cast, i.e. if a list is created paramaterized with < Integer >, get() should have a return type of Integer, not Comparable or Object.

I know that parameterized objects in Java can be created using things like < E > and < T >, but this does not allow me to require that the elements of the list be Comparable.

By the way, if you have any comments like "Just use ArrayList or LinkedList." or "Why are you using a custom list, stupid?", please keep them to yourself. I want to create a well-organized, efficient list system that doesn't fit with any existing structures. The Comparable requirement is necessary for the list to be sorted automatically.

If anyone could give me an idea of how to do this, it would be greatly appreciated.


Solution

  • You should declare your generic type parameter with an upper bound of Comparable to guarantee that the items are Comparable. However, Comparable itself has a type parameter, usually to itself. E.g. Integer implements Comparable<Integer>.

    Does T extends Comparable<T> work? Sure, but if Superclass implements Comparable<Superclass>, then a subclass Subclass also implements Comparable<Superclass>. To account for that possibility, introduce a wildcard with a lower bound of T.

    public class CustomParameterizedList<T extends Comparable<? super T>>
    

    This follows existing patterns in standard Java, such as Collections.sort, which defines T similarly.

    public static <T extends Comparable<? super T>> void sort(List<T> list)
    

    The Java Generics tutorial has explanations as to why <T extends Comparable<? super T>> is more flexible than <T extends Comparable<T>>.

    It isn't necessary that T be comparable to exactly itself. All that's required is that T be comparable to one of its supertypes. This give us:

    public static <T extends Comparable<? super T>> 
            T max(Collection<T> coll)