-1

I was looking at a mergeSort method, and i have some questions. There is a cast of Object into Comparable, that is an interface.

((Comparable)dest[j-1]).compareTo((Comparable)dest[j])

What the compiler exactly does when there is cast interface? The .compareTo method is not defined in Object class. An interface has only abstract method. How is possible to use in Object?

private static void mergeSort(Object src[], Object dest[], int low, int high) {
    int length = high - low;

    // Insertion sort on smallest arrays
    if (length < 7) {
        for (int i=low; i<high; i++)
          for (int j=i; j>low && ((Comparable)dest[j-1]).compareTo((Comparable)dest[j]) >0; j--)
              swap(dest, j, j-1);
        return;
    }
    // Recursively sort halves of dest into src
    int mid = (low + high)/2;
    mergeSort(dest, src, low, mid);
    mergeSort(dest, src, mid, high);

    // If list is already sorted, just copy from src to dest.  This is an
    // optimization that results in faster sorts for nearly ordered lists.
    if (((Comparable)src[mid-1]).compareTo((Comparable)src[mid]) <= 0) {
        System.arraycopy(src, low, dest, low, length);
        return;
    }
    // Merge sorted halves (now in src) into dest
    for(int i = low, p = low, q = mid; i < high; i++){
        if (q>=high || p<mid && ((Comparable)src[p]).compareTo(src[q])<=0)
            dest[i] = src[p++];
        else
            dest[i] = src[q++];
    }
}
  • Possible duplicate of [Casting objects in Java](https://stackoverflow.com/questions/5306835/casting-objects-in-java) – Jaroslaw Pawlak May 31 '18 at 15:39
  • Your question can be translated like "Is some Object *less than*, *equal to* or *greater than* other Object". Do you really think that this is the goal you want to achieve? – zlakad May 31 '18 at 15:41

2 Answers2

1

dest[j-1] is a reference, it refers an Object, this Object might has implemented Comparable.

With (Comparable)dest[j-1], you are telling the compiler Trust me, I 'm Comparable.

At runtime, if this object is comparable, that's fine. It not, ClassCastException will be thrown.

Object o = 1; // Integer is Comparable
System.out.println(((Comparable)(o)).compareTo(0)); // 1

Object o = new ArrayList<Integer>(); // ArrayList is not Comparable
System.out.println(((Comparable)(o)).compareTo(0)); // ClassCastException
xingbin
  • 27,410
  • 9
  • 53
  • 103
0

This is partly due to a hangover from the old days before generics when many of the core Java functions took Object as parameters and you had to cast stuff all over the place.

Also, the Arrays class can also sort intrinsic things like int etc.

What is happening here is that the mergeSort is assuming the object implements Comparable and calls it's compareTo method. This assumption will cause a fail fast ClassCastException so it's not a bad assumption.

TLDR: In most cases the object will implement Comparable so it is safe.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213