-1
public static void InsertionSort(Comparable[] a, int length){
        for (int i = 1; i < length; i++){
            for(int j = i; j > 0; j--){
                if(a[j].compareTo(a[i]) > 0){
                    Integer b = (Integer)a;
                    swap(b, j, i);
                }
                else{
                    break;
                }
            }
        }       
    }

public static void swap(Integer[] myArr,int a, int b){
        int temp;
        temp = myArr[a];
        myArr[a] = myArr[b];
        myArr[b] = temp;        
    }

Why is it not possible to downcast an interface to the instance implementing it? I would like to downcast a to an Integer type because a is comparable type. Then use the swap method which takes an Integer type but this is illegal.

Ninja Dude
  • 1,332
  • 4
  • 27
  • 54
  • `Integer` implements `Comparable`, not vise versa. For example http://stackoverflow.com/questions/7909081/assigning-a-parent-object-to-a-child-object-without-casting-in-java – Guy Feb 26 '17 at 09:58
  • 1
    Your swap method expects an array of Integer as first argument. You're passing an Integer. `a` is an array, and you're trying to cast it to Integer. An array can't possibly be an Integer. Read the error message: it should tell you exactly that. But the largest problem is that if your method can only sort Integers, and throws a ClassCastException for any other Comparable, it should take an array of Integer as argument, not an array of Comparable. And you shouldn't use raw types, too. – JB Nizet Feb 26 '17 at 09:58

1 Answers1

0

You don't need a cast. If you knew it was this type (Integer) you would make it an Integer in the first place.

public static void insertionSort(Comparable[] a) {
    for (int i = 1; i < a.length; i++)
        for (int j = i - 1; j >= 0; j--)
            if (a[i].compareTo(a[j]) > 0)
                swap(a, i, j);
            else
                break;      
}

public static void swap(Comparable[] myArr, int a, int b) {
    Comparable temp = myArr[a];
    myArr[a] = myArr[b];
    myArr[b] = temp;        
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130