I have a method:
public List sortStuff(List toSort) {
java.util.Collections.sort(toSort);
return toSort;
}
T
Collections.sort(List<T>) expects that T
must implement Comparable<? super T>
. It seems like Stuff
does implement Comparable
but doesn't provide the generic type argument.
Make sure to declare this:
public class Stuff implements Comparable<Stuff>
Instead of this:
public class Stuff implements Comparable
Do tou use this:
// Bad Code
public class Stuff implements Comparable{
@Override
public int compareTo(Object o) {
// TODO
return ...
}
}
or this?
// GoodCode
public class Stuff implements Comparable<Stuff>{
@Override
public int compareTo(Stuff o) {
// TODO
return ...
}
}
Sorting Generic Collections
There are two sorting functions defined in this class, shown below:
public static <T extends Comparable<? super T>> void sort(List<T> list);
public static <T> void sort(List<T> list, Comparator<? super T> c);
Neither one of these is exactly easy on the eyes and both include the wildcard (?) operator in their definitions. The first version accepts a List only if T extends Comparable directly or a generic instantiation of Comparable which takes T or a superclass as a generic parameter. The second version takes a List and a Comparator instantiated with T or a supertype.
You will need to change the return type of your method