Search code examples
javagenericsinterfacelimit

How can I limit a generic data structure to allow only elements of a specific interface?


Say I want to create a generic class for storing objects, but it shall only store objects that implement a specific interface. The interface goes something like this:

interface GenericSortedList<E> extends Iterable {    
   void add(E e);
   E get(String key);
}

Instances of GenericSortedList shall only be allowed to contain objects that implement the interface Comparable. How'd I do this?


Solution

  • You can introduce an upper bound on your type parameter E.

    interface GenericSortedList<E extends Comparable<E>> extends Iterable<E>
    

    Also make sure you pass E as the type parameter to Iterable, or else it will extend the raw form of the Iterable interface.

    To make it more flexible, you can put a wildcard and a lower bound on the E inside Comparable.

    interface GenericSortedList<E extends Comparable<? super E>> extends Iterable<E>
    

    This way, a superclass

    class Foo implements Comparable<Foo>
    

    and its subclass

    class Bar extends Foo
    

    can fit E's restrictions.