Question

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 ];
    }
Was it helpful?

Solution

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.

OTHER TIPS

Java uses Type Erasure to implement Generics so at run time the type AnyType isn't known and therefore you can't create an array of them. Look at this other question.

Because of generic type erasure, the compiler has has no idea what AnyType is (and hence can't create an array of it). But we know AnyType implements Comparable, so creating an array of Comparables is a safe solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top