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!

1
  • Is this the actual code that produces the error? Seeing the code for "Stuff" might help.
    – NilsH
    Mar 19, 2013 at 14:25

4 Answers 4

55

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
1
  • This works perfectly for me. I was implementing Comparator and changed it to Comparator<ObjectClassName> (for example) to match the parameters of the class's compare function.
    – ATL
    Oct 31, 2019 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 ...
    }

}
0
0

You will need to change the return type of your method

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.