我今天查看了一些Java代码,我发现了一些奇怪的语法:
public class Sample {
public int get()[] {
return new int[]{1, 2, 3};
}
}
Run Code Online (Sandbox Code Playgroud)
我认为无法编译并想修复我认为的错字,但后来我记得Java编译器确实接受了它!
有人可以帮我理解这是什么意思吗?它是一组函数吗?
我目前正在教学生作为导师编程惯例.我告诉他们,他们可以在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[] …Run Code Online (Sandbox Code Playgroud)