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 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.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With