Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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!

like image 699
IAmYourFaja Avatar asked Mar 19 '13 14:03

IAmYourFaja


People also ask

Are generics only limited to collections?

Just because collections are the most representative example of generics usage, you are not limited to them.

Why is generic introduced in java collection framework?

The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code stable by detecting the bugs at compile time. Before generics, we can store any type of objects in the collection, i.e., non-generic. Now generics force the java programmer to store a specific type of objects.


1 Answers

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
like image 143
PermGenError Avatar answered Sep 23 '22 01:09

PermGenError