Reputation: 681
I want to implement a simple sort function which sort the list and return the sorted list (very easy!). So I wrote this
public static <T extends List<? extends Comparable>> T sort(T objects)
{
Collections.sort(objects);
return objects;
}
The problem is when I try to sort a simple list it gives me this error
Error:(19, 20) error: no suitable method found for sort(T#1) method Collections.sort(List) is not applicable (cannot infer type-variable(s) T#2 (argument mismatch; T#1 cannot be converted to List)) method Collections.sort(List,Comparator) is not applicable (cannot infer type-variable(s) T#3 (actual and formal argument lists differ in length)) where T#1,T#2,T#3 are type-variables: T#1 extends List declared in method sort(T#1) T#2 extends Comparable declared in method sort(List) T#3 extends Object declared in method sort(List,Comparator) where CAP#1 is a fresh type-variable: CAP#1 extends Comparable from capture of ? extends Comparable
So what's the problem?!
Thanks in advance :)))
Upvotes: 0
Views: 90
Reputation: 384
As @Bejan George has pointed out, the generic type in this case should not be the the list but the comparable elements contained within the list.
The correct implementation would be:
public static <T extends Comparable> List<T> sort(List<T> objects) {
Collections.sort(objects);
return objects;
}
Upvotes: 2