问题描述
这是Mark Weiss教授在他的书中 Java中的数据结构和算法分析
This is from Professor Mark Weiss in his book Data Structures and Algorithm Analysis in Java
public class BinaryHeap<AnyType extends Comparable<? super AnyType>>{
private void enlargeArray( int newSize ){
AnyType [] old = array;
array = (AnyType []) new Comparable[ newSize ];
for( int i = 0; i < old.length; i++ )
array[ i ] = old[ i ];
}
}
我想知道为什么我们用a声明一个数组接口的类型可比较,因为我们必须将 Comparable []
转换为 AnyType []
?
I was wondering why do we declare an array with a type of interface Comparable since we have to convert the Comparable[]
to an AnyType[]
? Any design philosophy in there?
推荐答案
设计哲学是您无法实例化类型参数的数组,因此您必须使用合法的类型实例化数组。该方法已知的唯一合法类型是 Object
或 Comparable
的数组,而后者可获取有关以下内容的更多知识方式。
The design "philosophy" is that you can't instantiate an array of a type parameter, so you have to instantiate the array with a type that is legal. The only available legal types known to the method are array of Object
or of Comparable
, and the latter captures more knowledge about the type.
允许您向下转换为类型参数的数组,并且返回类型必须为该类型,因此需要向下转换。
You are allowed to downcast to an array of the type parameter, and the return type has to be that, so downcasting is required.
这是必然性的哲学。
这篇关于Java-为什么将数组声明为一种接口类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!