本文介绍了java.util.Collections上的Java泛型警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法:
public List<Stuff> sortStuff(List<Stuff> toSort) {
java.util.Collections.sort(toSort);
return toSort;
}
这会产生警告:
Type safety: Unchecked invocation sort(List<Stuff>) of the generic method sort(List<T>) of type Collections.
Eclipse说修复警告的唯一方法是添加 @SuppressWarnings unchecked)
到我的 sortStuff
方法。这似乎是一个内置于Java本身的东西的一个crummy方法。
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!
推荐答案
期望 T
必须实现 Comparable< ;? super T>
。看起来 Stuff
确实实现了 Comparable
,但不提供通用类型参数。
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.
确保声明:
public class Stuff implements Comparable<Stuff>
而不是这样:
public class Stuff implements Comparable
这篇关于java.util.Collections上的Java泛型警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!