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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With