2

I am trying to write a PriorityQueue which must be genericized to a Comparable. Here is the constructor:

public class DavidiArrayPriorityQueue <E extends Comparable<E>> implements PriorityQueue<E> {

    private E data[];
    private int numElements;

    //creates an empty priority queue with 10 spaces by default
    public DavidiArrayPriorityQueue(){

        data= (E[]) new Object[20];
        numElements=0;
    }

When I initialize it with

DavidiArrayPriorityQueue<Integer> test=new DavidiArrayPriorityQueue<Integer>();

It throws [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;

3
  • 3
    Indeed; an Object is not a Comparable. Commented Jan 26, 2014 at 1:16
  • Maybe you should use a List instead of an array? Commented Jan 26, 2014 at 1:19
  • 1
    @OliCharlesworth: Or, more to the point: an Object[] is not a Comparable[]. Commented Jan 26, 2014 at 1:24

1 Answer 1

4

The element-type of an array is actually part of the array, known at runtime. So when you write new Object[], you are creating an array with element-type Object, and even if your intent is that the elements of the array will all always have type (say) Comparable, you still can't cast it to Comparable[].

In your case, you're casting it to E[]. Due to erasure, the cast can't be fully enforced at runtime, so it's downgraded to a cast to Comparable[]; so, technically speaking, you could trick the compiler into allowing this, by writing (E[]) new Comparable[]. But that's a bad idea, because then you have an array expression of type E[] whose element-type is not actually E. You've circumvented the type system, and this can cause confusing errors later on.

It's better to just have data be of type Object[] (or perhaps Comparable<?>[]), and perform the necessary casts to E. This will result in compiler warnings, because the compiler won't be able to check those casts, either, but at least you can verify that your code is correct and correctly preserves the type system (and then suppress the warnings, with a comment).

Sign up to request clarification or add additional context in comments.

4 Comments

Casting new Comparable<?>[] to E[] should be fine as long as the array isn't exposed outside of the class (where it might be assigned to a reifiable type).
@PaulBellora, that situation arises in the classes of the Collections framework in the java.util
Like in Vector. Here an Object[] is used for storage and for obtaining elements, type casting is used.
@ambigram_maker Understood. Yes that's perfectly fine too, except perhaps more unchecked warnings to suppress.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.