Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 356
victorio Avatar asked Nov 26 '25 12:11

victorio


1 Answers

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

like image 62
JEY Avatar answered Nov 28 '25 01:11

JEY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!