I'm taking a data structures course, and we're using Data Structures and Algorithm Analysis in Java 2nd Edition by Mark Weiss. In his BinaryHeap implementation, his constructor creates a Comparable[] array that is casted to AnyType[]. Do you have any idea as to why he does this instead of just creating a new AnyType[]?
I understand the structure of the BinaryHeap, but I want to be up to speed on generics. The class declaration is straightforward enough, make sure that AnyType extends a type that is Comparable to AnyType or any superclass up AnyType's inheritance hierarchy (in case AnyType is a subclass of a type and doesn't need to change its compareTo method in order to function).
However, the line, array = (AnyType[]) new Comparable[ capacity + 1 ];
, makes no sense to me. Isn't AnyType already a Comparable? What ramifications are there for just writing array = new AnyType[ capacity + 1 ];
?
The full class source can be found on his site, but here are the parts I'm concerned with:
public class BinaryHeap<AnyType extends Comparable<? super AnyType>>
{
private int currentSize; // Number of elements in heap
private AnyType [ ] array; // The heap array
/**
* Construct the binary heap.
* @param capacity the capacity of the binary heap.
*/
public BinaryHeap( int capacity )
{
currentSize = 0;
array = (AnyType[]) new Comparable[ capacity + 1 ];
}
You can't create arrays of a generic type because the type information doesn't exist at runtime. As AnyType
extends Comparable
, that is the only 'concrete' type that can be used.
The cast to AnyType[]
is simply to ensure compile-time warnings are given if there's a mistake; that cast won't exist in the resulting bytecode instructions. Similarly, the array
class variable will be a Comparable[]
in the resulting bytecode.