简体   繁体   中英

Java Class Cast Exception when creating Generic Array

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;

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM