Java generics warnings on java.util.Collections

I have a method:

public List<Stuff> sortStuff(List<Stuff> toSort) { java.util.Collections.sort(toSort); return toSort; } 

This raises 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. This seems like a meek way to do something that is built into Java.

Is this really my only option here? Why or why not? Thanks in advance!

+6
source share
4 answers

Collections.sort(List<T>) expects T to implement Comparable<? super T> Comparable<? super T> . It seems that Stuff implements Comparable , but does not provide a generic type argument.

Be sure to declare this:

 public class Stuff implements Comparable<Stuff> 

Instead of this:

 public class Stuff implements Comparable 
+25
source

Use this:

 // Bad Code public class Stuff implements Comparable{ @Override public int compareTo(Object o) { // TODO return ... } } 

or that?

 // GoodCode public class Stuff implements Comparable<Stuff>{ @Override public int compareTo(Stuff o) { // TODO return ... } } 
+3
source

You will need to change the type of the returned method

0
source

Sort shared collections

This class defines two sorting functions, 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); 

None of them are easy on the eyes, and both include a wildcard (?) Operator in their definitions. The first version only accepts a list if T extends Comparable directly or a generic Comparable instance that accepts T or a superclass as a generic parameter. The second version accepts a list and a comparator created using T or a supertype.

0
source

All Articles