简体   繁体   English

Java方法签名后奇怪的“[]”

[英]Weird “[]” after Java method signature

I looked at some Java code today, and I found some weird syntax: 我今天查看了一些Java代码,我发现了一些奇怪的语法:

public class Sample {
  public int get()[] {
    return new int[]{1, 2, 3};
  }
}

I thought that can't compile and wanted to fix what I thought was a typo, but then I remembered the Java compiler did actually accept it! 我认为无法编译并想修复我认为的错字,但后来我记得Java编译器确实接受了它!

Can someone please help me understand what it means? 有人可以帮我理解这是什么意思吗? Is it an array of functions? 它是一组函数吗?

It's a method that returns an int[] . 这是一个返回int[]

Java Language Specification (8.4 Method Declarations) Java语言规范 (8.4方法声明)

For compatibility with older versions of the Java platform, a declaration form for a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the parameter list. 为了与旧版本的Java平台兼容,允许返回数组的方法的声明表单放置(部分或全部)在参数列表之后形成数组类型声明的空括号对。

This is supported by the obsolescent production: 这是过时的生产支持:

MethodDeclarator : MethodDeclarator
MethodDeclarator [ ] MethodDeclarator []

but should not be used in new code. 但不应在新代码中使用。

That's a funny Question. 这是一个有趣的问题。 In java you can say int[] a; 在java中你可以说int[] a; , as well as int a[]; ,以及int a[]; .
From this perspective, in order to get the same result just need to move the [] 从这个角度来看,为了获得相同的结果,只需要移动[]
and write public int[] get() { . 并写入public int[] get() {
Still looks like the code came from an obfuscator... 仍然看起来代码来自混淆器......

As there is a C tag, I'll point out that a similar (but not identical) notation is possible in C and C++: 由于存在C标记,我将指出C和C ++中可能存在类似(但不完全相同)的表示法:

Here the function f returns a pointer to an array of 10 ints. 这里函数f返回一个指向10个int数组的指针。

int tab[10];

int (*f())[10]
{
    return &tab;
}

Java simply doesn't need the star and parenthesis. Java根本不需要星号和括号。

java's syntax allows for the following: java的语法允许以下内容:

int[] intArr = new int[0];

and also 并且

int intArr[] = new int[0];

which looks more fmiliar coming from the c-style syntax. 来自c风格语法看起来更加陌生。

so too, with a function, the name can come before or after the [], and the type is still int[] 同样,使用函数,名称可以在[]之前或之后,并且类型仍然是int []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM