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!
Just because collections are the most representative example of generics usage, you are not limited to them.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With