简体   繁体   English

在Java中对未知类型的列表进行排序

[英]Sorting list with unknown type in Java

I have this list in a method: 我在一个方法中有这个列表:

List<? extends Object> objects;

or it can be also: 或者它也可以是:

List<?> objects;

I wanted to sort it this way, with Java 8 lambda: 我想用Java 8 lambda这样排序:

objects.sort((p1, p2) -> p1.compareTo(p2));

But it says: 但它说:

The method compareTo(capture#6-of ?) is undefined for the type capture#6-of ? 方法compareTo(捕获#6-of?)未定义类型捕获#6-of?

I also tried with generic type: 我也尝试过泛型类型:

List<O extends Object> objects;

But then it says: 但随后它说:

The method compareTo(O) is undefined for the type O 对于类型O,方法compareTo(O)未定义

How could I sort a list like this way? 我怎么能这样排序一个列表? I need it in my abstract class, where it recognizes the list field by reflection, and it can sort it. 我需要它在我的抽象类中,它通过反射识别列表字段,并且可以对其进行排序。

compareTo is available for object that implements Comparable interface. compareTo可用于实现Comparable接口的对象。 If you want to do that you should use 如果你想这样做,你应该使用

List<? extends Comparable> objects;

For a clean code check @Holger answer 要获得干净的代码,请查看@Holger的答案

If you are confident, that all elements of the list are mutually comparable, that is, they are not only implementing Comparable , but also Comparable<CommonBaseType> , eg while String and Integer instances are Comparable , you can't compare a String with an Integer and must not have instances of both types in your list, then you can bypass the compile-time checking using 如果您有信心,列表中的所有元素都是可以相互比较的,也就是说,它们不仅实现了Comparable ,而且还实现了Comparable<CommonBaseType> ,例如,当StringInteger实例是Comparable ,您无法将StringInteger并且列表中不能包含这两种类型的实例,然后您可以绕过编译时检查

objects.sort(null);

of course, with all consequences of bypassing the compile time type checks. 当然,绕过编译时类型检查的所有后果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM