Java 中创建数组的语法如下:
ArrayCreationExpression:
new PrimitiveType DimExprs [Dims]
new ClassOrInterfaceType DimExprs [Dims]
new PrimitiveType Dims ArrayInitializer
new ClassOrInterfaceType Dims ArrayInitializer
DimExprs:
DimExpr {DimExpr}
DimExpr:
{Annotation} [ Expression ]
Dims:
{Annotation} [ ] {{Annotation} [ ]}
为什么在这里:new PrimitiveType DimExprs [Dims]
Dims
在括号里?如果它在括号中,那么我可以这样写:new int [2][2] [[] []]
其中 [2][2]
是 DimExprs
部分和 [] []
是 Dims
部分。我在这里做错了什么?
最佳答案
答案似乎就在我眼前,但不知何故我错过了。这是来自 Java 规范的原因:
The syntax [x] on the right-hand side of a production denotes zero or one occurrences of x. That is, x is an optional symbol. The alternative which contains the optional symbol actually defines two alternatives: one that omits the optional symbol and one that includes it.
这意味着您可以编写 String[][][] s = new String[2][][];
链接:https://docs.oracle.com/javase/specs/jls/se8/html/jls-2.html#jls-2.4
关于java - Java 中的数组创建语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46881030/