I have generic class of TreeNode:
public class TreeNode {
public E key;
public int num_of_children;
public TreeNode [] children;
public TreeN
Because the Java Language Specification writes:
An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType.
It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type (§4.7). Otherwise, the ClassOrInterfaceType may name any named reference type, even an abstract class type (§8.1.1.1) or an interface type (§9).
The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard.
It is not clear to me why they require this. Certainly, the component type of the array must be available at runtime, and it would be misleading for the programmer if it were different from the type specified in the source code. Consider:
E[] a = new E[10];
Here, it would be bad if the compiler used the erasure of E
as the array component type, as the programmer might well depend upon the array to check that nothing but instances of E
is stored in it.
It's less clear what harm would come from allowing:
List[] lists = new List[10];
The only thing that comes to mind is that assigning an array element would amount to an unchecked cast, because the array would check the element is a List
, but not that it is a List
, and thus fail to throw an ArrayStoreException
.
In practice, you can safely suppress this warning as long as you remain aware that the array will not check the type parameters of its component type.