14

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!

IAmYourFaja
  • 55,468
  • 181
  • 466
  • 756
  • Is this the actual code that produces the error? Seeing the code for "Stuff" might help. – NilsH Mar 19 '13 at 14:25

4 Answers4

54

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
Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • This works perfectly for me. I was implementing Comparator and changed it to Comparator (for example) to match the parameters of the class's compare function. – ATL Oct 31 '19 at 17:14
6

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 ...
    }

}
Alepac
  • 1,833
  • 13
  • 24
0

You will need to change the return type of your method

astra03
  • 505
  • 1
  • 7
  • 18
0

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.

Achintya Jha
  • 12,735
  • 2
  • 27
  • 39