简体   繁体   中英

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:

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

But it says:

The method compareTo(capture#6-of ?) is undefined for the type capture#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

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. If you want to do that you should use

List<? extends Comparable> objects;

For a clean code check @Holger answer

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

objects.sort(null);

of course, with all consequences of bypassing the compile time type checks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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