我有以下内联比较器。
private static class SampleSorter implements Comparator<SampleClass>{
public int compare(SampleClass o1, SampleClass o2) {
if (o1 instanceof Comparable) {
return ((Comparable) o1).compareTo(o2);
} else if (o2 instanceof Comparable) {
return -((Comparable) o2).compareTo(o1);
}
return 0;
}
}
这会生成以下警告:
Comparable
is a raw type. References to generic typeComparable<T>
should be parameterized
如果我按照建议参数化类型:
if (o1 instanceof Comparable) {
return ((Comparable<SampleClass>) o1).compareTo(o2);
然后我收到警告...
Type safety: Unchecked cast from
SampleClass
toComparable<SampleClass>
如果我进行类型检查:
if (o1 instanceof Comparable<SampleClass>) {
return ((Comparable<SampleClass>)o1).compareTo (o2);
我收到以下错误:
Cannot perform instanceof check against type
Comparable<SampleClass>
. Use the formComparable<?>
instead since generic type information will be erased at runtime
再说一遍,如果我遵循错误消息的建议:
if (o1 instanceof Comparable<?>) {
return ((Comparable<?>)o1).compareTo (o2);
我收到此错误:
The method
compareTo(capture#4-of ?)
in the typeComparable<capture#4-of ?>
is not applicable for the arguments(SampleClass)
现在我不知道如何继续,我真的更喜欢没有警告和错误的代码。 如何生成具有所需行为的无警告代码?
最佳答案
您遇到的问题是编译器无法知道您所做的事情是安全的。相反,您必须相信您知道自己在做什么,并且可以添加此注释
@SuppressWarnings("unchecked")
方法或类和警告消失。
关于java - java 中的类型检查和泛型会生成警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8572982/