victorio
victorio

Reputation: 6676

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.

Upvotes: 2

Views: 1515

Answers (2)

JEY
JEY

Reputation: 7133

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

Upvotes: 8

Holger
Holger

Reputation: 298559

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>, e.g. 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.

Upvotes: 5

Related Questions