[英]Cast instance of Object with Comparable
I was looking at a mergeSort method, and i have some questions.我在看一个 mergeSort 方法,我有一些问题。 There is a cast of Object into Comparable, that is an interface.
有一个 Object 到 Comparable 的转换,也就是一个接口。
((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. .compareTo
方法未在Object
类中定义。 An interface has only abstract method.接口只有抽象方法。 How is possible to use in Object?
如何在 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++];
}
}
dest[j-1]
is a reference, it refers an Object
, this Object
might has implemented Comparable
. dest[j-1]
是一个引用,它指的是一个Object
,这个Object
可能已经实现了Comparable
。
With (Comparable)dest[j-1]
, you are telling the compiler Trust me, I 'm Comparable .使用
(Comparable)dest[j-1]
,您是在告诉编译器相信我,我是 Comparable 。
At runtime, if this object is comparable, that's fine.在运行时,如果这个对象是可比较的,那很好。 It not,
ClassCastException
will be thrown.否则,会抛出
ClassCastException
。
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
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.这部分是由于过去泛型之前的遗留问题,当时许多核心 Java 函数都将
Object
作为参数,而您必须到处投射东西。
Also, the Arrays
class can also sort intrinsic things like int
etc.此外,
Arrays
类还可以对int
等内部事物进行排序。
What is happening here is that the mergeSort
is assuming the object implements Comparable and calls it's compareTo
method.这里发生的事情是
mergeSort
假设对象实现Comparable并调用它的compareTo
方法。 This assumption will cause a fail fast ClassCastException so it's not a bad assumption.这个假设会导致一个快速失败的ClassCastException,所以这不是一个糟糕的假设。
TLDR: In most cases the object will implement Comparable
so it is safe. TLDR:在大多数情况下,对象将实现
Comparable
因此它是安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.