Reputation: 56912
I have a method:
public List<Stuff> sortStuff(List<Stuff> toSort) {
java.util.Collections.sort(toSort);
return toSort;
}
This produces a warning:
Type safety: Unchecked invocation sort(List<Stuff>) of the generic method sort(List<T>) of type Collections.
Eclipse says the only way to fix the warning is to add @SuppressWarnings("unchecked")
to my sortStuff
method. That seems like a crummy way to do with something that is built into Java itself.
Is this really my only option here? Why or why not? Thanks in advance!
Upvotes: 14
Views: 11549
Reputation: 46408
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
Upvotes: 55
Reputation: 1831
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 ...
}
}
Upvotes: 6
Reputation: 12843
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.
Upvotes: 0