-1

I don't understand why I get an Unchecked cast from Object to Compareable<Object> because it is inside of a area that is only entered, if the instance is of a Compareable type. Can someone explain this to me and maybe give a solution, thanks.

My code looks like this. The problem is at line 8 and 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;

}
7heViking
  • 7,137
  • 11
  • 50
  • 94

1 Answers1

1

When it produces an unchecked warning as it doesn't know that your object is Comparable to Object. In fact it is highly unlikely that it is, e.g. Integer is Comparable<Integer> but this is the simplest way to get this code to compile

I suggest you use

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

or

Comparable cOne = (Comparable) oOne;

BTW, You can't just return 1 at the end as you have you ensure that if compare(a, b) > 0 then compare(b, a) < 0

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    It's not the cast to `Comparable` that's causing problems, it's the cast to `Comparable`. See the accepted answer from the dup, above. – Erick G. Hagstrom Sep 24 '15 at 14:37
  • @ErickG.Hagstrom Good point, in this cases the warning is valid, unless you assume that `a` and `b` will always be `Comparable` which may, or may not be correct. – Peter Lawrey Sep 24 '15 at 14:43