array of parameterized types

Arrays of concrete paramaterized types are inherently broken. Remember arrays are covariant and the array type check is a runtime operation. At runtime all the generics have been type erased, so the Array Store check can’t tell <Pair<ParseNode, ParseNode>> from <Pair<BigInteger,IOException>>.

The fundamental contract of a generic is “I, the compiler, promise that if you write code that generates no warnings, you will never get a class cast exception at runtime.”

Neither can the compiler guarantee to you that it will be able to give you a compile time error if something that is not an ArrayList<Pair<ParseNode,ParseNode>> is put into that array. Nor can the runtime system guarantee you will get an ArrayStoreException (like the Language Specification says it will) if you add the wrong type, rather than a ClassCastException later when you take it back out. (The second part is really why it’s actually illegal rather than just a warning, it would result in an array that doesn’t obey the language specification.)

So it doesn’t let you declare them that way and forces you to acknowledge the ‘unsafe’ warning. That way it has said “I told you I can’t guarantee there will not be any class cast exceptions as a result of using this array, it’s on you to make sure you only put the right things in here.”

Leave a Comment