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!
Collections.sort(List<T>)
expects that T
must implement Comparable<? super T>
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 ...
}
}
您需要更改方法的返回类型
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.