Java Error: New Generic TreeNode Array

后端 未结 2 1648
無奈伤痛
無奈伤痛 2021-01-23 08:43

I have generic class of TreeNode:

public class TreeNode {
public E key;
public int num_of_children;
public TreeNode [] children;


public TreeN         


        
2条回答
  •  情话喂你
    2021-01-23 09:42

    Things like new TreeNode[] and new TreeNode[] are disallowed by Java. The only things you can do are new TreeNode[] and new TreeNode[] (unbounded wildcard parameter).

    The reason for this is a little complicated, but instructive. Arrays in Java know their component type at runtime, and every time you put something in, it checks to see if it's an instance of the component type, and if not, throws an exception (this is related to how array types are covariant and therefore inherently unsafe at compile time).

    Object[] foo = new Integer[5];
    foo[2] = "bar"; // compiles fine, but throws ArrayStoreException at runtime
    

    Now add generics. The problem with a generic component type is that, there is no way for you to check if an object is an instance of say, TreeNode at runtime (as opposed to TreeNode), since generics are erased from runtime types. It can only check TreeNode, but not the component type. But programmers might have expected this checking and exception throwing behavior from arrays, since it normally works. So to avoid this surprise failure, Java disallows it. (In most code, you won't run into this problem anyway because you won't be mixing objects of the same type but different type parameters. But it is theoretically possible to come up.)

    Of course, you can simply work around the problem by creating an array of raw or wildcard parameter type, and then casting to the proper type, e.g. (TreeNode)new TreeNode[5]. What's the difference? Well, that's an unchecked cast, which generates a warning, and you, the programmer, takes responsibility for all the unsafe things that might happen later. If it does something unexpected, the compiler can say, "we told ya so!".

提交回复
热议问题