Java数组约定:String [] args vs. String args []

Mar*_*oma 21 java coding-style conventions

我目前正在教学生作为导师编程惯例.我告诉他们,他们可以在Oracle Code Conventions中找到大多数约定.

在我上一篇教程中,一名学生询问:

public static void main(String args[])
Run Code Online (Sandbox Code Playgroud)

要么

public static void main(String[] args)
Run Code Online (Sandbox Code Playgroud)

是按惯例书写的,或是否存在差异.我之前从未见过第一个版本,所以我非常肯定第二个版本是一个约定.但我没有这个来源.

你能给我一个消息来源(最好是来自oracle,就像我上面链接过的页面一样),这些消息可以说清楚哪一个是常规的?

两种表达方式的等价性

我知道两个表达式都是等价的:

JLS 7,第 292州:

An array type is written as the name of an element type followed 
by some number of empty pairs of square brackets []. 
Run Code Online (Sandbox Code Playgroud)

而且还在p.293:

The [] may appear as part of the type at the beginning of the declaration, 
or as part of the declarator for a particular variable, or both.

For example:
    byte[] rowvector, colvector, matrix[];
This declaration is equivalent to:
    byte rowvector[], colvector[], matrix[][];
Run Code Online (Sandbox Code Playgroud)

但这对于会议问题没有帮助.

所以它们是相同的(不是规格,但这里是一个来源).它们在一个小例子中产生相同的字节码,所以我非常确定它们在实践中也是相同的.

Abu*_*kar 19

这不是来自甲骨文,但我认为这会有所帮助.

它来自Kathy Sierra的书籍SCJP Sun认证程序员Java 6

int[] key;
int key [];
Run Code Online (Sandbox Code Playgroud)

声明数组引用时,应始终将数组括号放在声明的类型之后,而不是在标识符(变量名称)之后.这样,任何阅读代码的人都可以很容易地告诉我,例如,key是对int数组对象的引用,而不是int原语.

  • +1,我也认为数组括号属于不是变量名的类型. (6认同)