Why declare an array as an interface type?

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 we are declaring an array with the Comparable interface type, since we have to convert Comparable[] to AnyType[] ? Any design philosophy out there?

+7
java arrays
source share
1 answer

The “philosophy” of design is that you cannot create an array of type parameters, so you need to instantiate an array with a type that is legal. The only legal types available to the method are the Object or Comparable , and the latter captures more knowledge about the type.

You are allowed to drag the array into the type parameter, and the type of the return value should be like that, so lowering is required.

This is the “philosophy” of necessity.

+4
source share

All Articles