-1

我不明白为什么我会得到一个,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;

}
4

1 回答 1

1

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

我建议你使用

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

或者

Comparable cOne = (Comparable) oOne;

顺便说一句,你不能只是return 1在最后,因为你有你确保如果compare(a, b) > 0那时compare(b, a) < 0

于 2015-09-24T14:30:57.800 回答