Why declare an array as a type of Interface?

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

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?


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.

It's the "philosophy" of necessity.

链接地址: http://www.djcxy.com/p/96032.html

上一篇: Autocomplete von HTML中可用的CSS类JavaScript中的jQuery在Eclipse中

下一篇: 为什么要将数组声明为一种接口?