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