Java Class Cast Exception when creating Generic Array

前端 未结 1 862
生来不讨喜
生来不讨喜 2020-12-21 10:48

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

public class DavidiArrayPriorityQueue 

        
相关标签:
1条回答
  • 2020-12-21 11:30

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

    0 讨论(0)
提交回复
热议问题