为什么 Java 数组声明使用大括号?
我想知道为什么 Java 数组声明使用大括号而不是标准括号。如图所示。我想这可能需要进一步理解大括号,但这现在已经在我的议程上了。
Object[] tableHeaders = {"Cars","Trucks","Tacos"};
这是正确的,而不是相反。
Object[] tableHeaders = ("Cars","Trucks","Tacos");
I would like to know why Java array declarations use curly brackets as opposed to the standard parenthesis. As illustrated here. I imagine this may take further understanding of curly brackets in general, but this specifically is on my agenda right now.
Object[] tableHeaders = {"Cars","Trucks","Tacos"};
This is correct, as opposed to.
Object[] tableHeaders = ("Cars","Trucks","Tacos");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
大括号通常表示集合和系综,而圆括号通常表示类 C 语言中的参数。
很久以前,人们就习惯了这种与 C 的约定。我非常确定它在 Java 中以这种方式工作,以保持与旧语言的某种语法一致性。
Curly brackets usually denotes sets and ensembles while parenthesis usually denotes parameters in C-like languages.
A long time ago, people got used to having this kind of convention with C. I'm pretty sure that it works this way in Java to keep some kind of syntax consistency with older languages.
我不能说为什么 James Gosling 等人选择了这个特定的替代方案...
但是,使用圆括号而不是大括号会给 Java 语法带来严重的歧义问题。考虑以下示例:
圆括号是否表示数组构造函数,或者它们是正常表达式语法的一部分吗?
现在可以想出一些复杂的优先规则来解决这个问题,但这让程序员和编译器编写者的生活变得困难。
(在语法层面,Java 解析器需要处理以下歧义:
在上面的示例中,
("Cars")
匹配 ArrayInitializer 和 Expression 产生式...如果您对数组使用圆括号决定哪个是正确的含义需要查看声明的变量类型......然后对变量初始化器进行上下文敏感的解析。)我想说他们在不使用圆括号作为数组初始值设定项方面做出了正确的选择。
方括号也不起作用。考虑尝试解释这一点……
与
与
I can't say why James Gosling et al chose this particular alternative ...
However, using round brackets instead of curly brackets would create a serious ambiguity problem for the Java grammar. Consider the following example:
Do the round brackets denote an array constructor, or are they part of the normal expression expression syntax?
Now it would be possible to come up with some complicated precedence rules to cover this, but that makes life difficult for both programmers and compiler writers.
(At the grammatical level, a Java parser needs to deal with ambiguity in:
In the example above,
("Cars")
matches both the ArrayInitializer and Expression productions ... if you use round brackets for array initializers. Deciding which is correct meaning would require looking at the declared variable type ... followed by context sensitive parsing of the VariableInitializer. Nasty.)I'd say they made the right choice in not using round brackets for array initializers.
Square brackets won't work either. Consider trying to explain this ...
versus
versus
在大多数使用最广泛的基于 Algol 的编程语言中,数组是使用花括号声明的。
In most Algol-based programming languages, which are the most widely-used languages, arrays are declared using the curly braces.