As well-known, generic array creation is not supported in Java. For example, the following code will error out with generic array creation
during the build,
Deque<TreeNode>[] stacks = {new ArrayDeque(), new ArrayDeque()};
However, the following code of creating such an array works,
Deque<TreeNode>[] stacks = new ArrayDeque[2];
I would like to know the rationale behind why the behaviors are different between these two logic.
When they say "parameterised array creation is not allowed", they mean that this specific syntax is not allowed:
new T<U>[]
where T
and U
are types. Note that this has nothing to do with the declared type of the array. It's perfectly fine to declare an array to be of type Deque<TreeNode>
, so the problem is on the right side of the =
, not the left.
In the second case, you are doing new ArrayDeque[2]
, obviously not violating the rule, as it is not in the form new T<U>[]
.
In the first case, you are using an array initialiser, making the compiler infer what type of array you are trying to create, and the compiler does so by looking at the left hand side. So the first line is equivalent to:
Deque<TreeNode>[] stacks = new Deque<TreeNode>[] {new ArrayDeque(), new ArrayDeque()};
which is not allowed. It is in the form new T<U>[]
.