Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Why declare an array as a type of Interface?

Tags:

java

arrays

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?

like image 608
liuxl Avatar asked Apr 14 '17 16:04

liuxl


People also ask

Is array an interface in Java?

The Array interface provides methods for bringing an SQL ARRAY value's data to the client as either an array or a ResultSet object. If the elements of the SQL ARRAY are a UDT, they may be custom mapped.

Why do we declare array in Java?

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

Can I make a array in an interface Java?

Of course you can create an array whose type is an interface. You just have to put references to concrete instances of that interface into the array, either created with a name or anonymously, before using the elements in it.

Is an array an interface?

Arrays define a structure, not an interface These methods make up an interface that explains what you can do with the object. In contrast to arrays, the Collection API provides many useful methods to access the elements.


1 Answers

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.

like image 94
Lew Bloch Avatar answered Oct 14 '22 19:10

Lew Bloch