Zaffaro
Zaffaro

Reputation: 131

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?

Upvotes: 1

Views: 118

Answers (2)

rgettman
rgettman

Reputation: 178263

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.

Upvotes: 4

Branislav Lazic
Branislav Lazic

Reputation: 14806

Basically:

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

Upvotes: 2

Related Questions