Weird “[]” after Java method signature

后端 未结 4 1184
北海茫月
北海茫月 2020-12-23 08:48

I looked at some Java code today, and I found some weird syntax:

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

4条回答
  •  情歌与酒
    2020-12-23 09:22

    It's a method that returns an int[].

    Java Language Specification (8.4 Method Declarations)

    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.

    This is supported by the obsolescent production:

    MethodDeclarator:
        MethodDeclarator [ ]

    but should not be used in new code.

提交回复
热议问题