如何限制通用数据结构以仅允许特定接口的元素?

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

假设我想创建一个通用的 class 来存储对象,但它只能存储实现特定接口的对象。 界面是这样的:

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

GenericSortedList 的实例只允许包含实现接口 Comparable 的对象。我是怎么做到的?

基本上:

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

您可以在类型参数上引入上限 E

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

还要确保将 E 作为类型参数传递给 Iterable,否则它将扩展 Iterable 接口的原始形式。

为了使其更灵活,您可以在 Comparable 内的 E 上放置一个通配符和一个下限。

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

这样,一个超类

class Foo implements Comparable<Foo>

及其子类

class Bar extends Foo

可以满足E的限制。