java为什么“未经检查的强制转换自…”
我不明白为什么我会得到一个Unchecked cast from Object to Compareable<Object>
,因为如果实例是可比较的类型,它位于只输入的区域内。谁能给我解释一下,也许能给我一个解决办法,谢谢
我的代码看起来像这样。问题出在第8行和第9行:
public int compare(Object one, Object two) {
if (one instanceof Vector && two instanceof Vector) {
Vector<? extends Object> vOne = (Vector<?>)one;
Vector<? extends Object> vTwo = (Vector<?>)two;
Object oOne = vOne.elementAt(index);
Object oTwo = vTwo.elementAt(index);
if (oOne instanceof Comparable && oTwo instanceof Comparable) {
Comparable<Object> cOne = (Comparable<Object>)oOne;
Comparable<Object> cTwo = (Comparable<Object>)oTwo;
if (ascending) {
return cOne.compareTo(cTwo);
} else {
return cTwo.compareTo(cOne);
}
}
}
return 1;
}
# 1 楼答案
当它不知道您的对象是
Comparable
到Object
时,会生成未选中的警告。事实上,这是极不可能的,例如Integer
是Comparable<Integer>
,但这是编译此代码的最简单方法我建议你用
或
顺便说一句,你不能只在结尾处
return 1
,你要确保如果compare(a, b) > 0
那么compare(b, a) < 0