开发者

Why do Java array declarations use curly brackets?

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 开发者_如何学Gobrackets 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");


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.


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:

Object[] tableHeaders = ("Cars");

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:

VariableInitializer:
    ArrayInitializer
    Expression

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 ...

... = new Object[]["Cars"];  // 1-D array

versus

... = new Object[21][];      // 2-D array

versus

... = new Object[][];        // is that 1-D or 2-D?


In most Algol-based programming languages, which are the most widely-used languages, arrays are declared using the curly braces.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜