为什么 "Unchecked cast from..."

Why "Unchecked cast from..."

我不明白为什么我会得到一个 Unchecked cast from Object to Compareable<Object>,因为如果实例是 Compareable 类型,它就在一个只能输入的区域内。谁能给我解释一下,也许能给出一个解决方案,谢谢。

我的代码如下所示。问题出在第 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;

}

当它产生未经检查的警告时,因为它不知道您的对象是 ComparableObject。事实上,它是极不可能的,例如IntegerComparable<Integer> 但这是编译此代码的最简单方法

我建议你使用

@SuppressWarning("checked")
Comparable<Object> cOne = (Comparable<Object>)oOne;

Comparable cOne = (Comparable) oOne;

顺便说一句,你不能只在最后 return 1 因为你要确保 if compare(a, b) > 0 then compare(b, a) < 0