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++];
}
}