如何在Java中对generics类型列表进行排序

我有一组所有共享一些共同属性的类,所以我让它们都扩展了一个共同的基类BaseEntity 。 所以我有,例如Foo extends BaseEntityBar extends BaseEntity

我还希望这些FooBar对象的列表是可排序的,所以我已经实现了Comparable 。 我将类定义为Foo extends BaseEntity implements ComparableBar extends BaseEntity implements Comparable ,并且FooBar的列表的排序按预期工作 – 当然,排序的细节是不同的在不同的子类中。 但是,当我事先不知道我是否会有FooBar时,我无法弄清楚如何进行分类工作。 例如,此代码无法编译:

 public class UtilityClass { ...bunch of stuff... List values; public List sort() { Collections.sort(values); return values; } ...more methods... } 

错误消息Bound mismatch: The generic method sort(List) of type Collections is not applicable for the arguments (List). The inferred type T is not a valid substitute for the bounded parameter <T extends Comparable> Bound mismatch: The generic method sort(List) of type Collections is not applicable for the arguments (List). The inferred type T is not a valid substitute for the bounded parameter <T extends Comparable>

我认为问题是我试图对BaseEntity对象列表进行排序,而BaseEntity本身并没有实现Comparable 。 但是现在我遇到了一个问题:使BaseEntity对象与其他BaseEntity对象相比是唯一合理的事情,但是当我将implements Comparable添加到BaseEntity ,编译器告诉我现在我遇到了问题,因为我的Foo类是试图同时实现ComparableComparable ,这显然是不允许的。

我知道我可以通过删除implements Comparable并实现Comparable来回避这个问题,但是然后我的compareTo方法将不得不做丑陋的转换,我认为这正是使用generics的那种问题应该是避免。

我真正想要做的是在BaseEntity的签名中指定它的所有子类都是Comparable ,但仅限于同一子类的实例。

感激地收到任何帮助。 谢谢!

使用交集类型,如下所示:

 public class MyList> {...} 

这指定T必须既是BaseEntity 是自身Comparable

不要使用Collections.sort(List) ,而是使用Collections.sort(Lst, Comparator) 。 将比较代码写入比较器。

尝试这个:

 static > sort(T[] array); 

这是完成任务的最通用规范。 基本上,它断言,T是一种可以与自身进行比较的类型。