java - Java 中的数组创建语法

标签 java arrays syntax

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/

相关文章:

java - 使用自签名证书连接到服务器

javascript - 如果我想为数组的单个索引添加多个元素,如何在 javascript 中填充数组

java - 从数组中获取随机值

c - 这是一个有效的 C ifdef 结构吗?有没有更好的办法?

java - 如何在 Spring 中注入(inject)一个 List 实例?

java - 可以 :select submit palette values in Tapestry 5. 3.6 吗?

C结构语法问题

php - 解析错误: syntax error, unexpected T_OBJECT_OPERATOR, expecting ')' [closed]

java - 递归方法的数学公式

Javascript 数组速记