Weird “[]” after Java method signature

后端 未结 4 1166
北海茫月
北海茫月 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:09

    As there is a C tag, I'll point out that a similar (but not identical) notation is possible in C and C++:

    Here the function f returns a pointer to an array of 10 ints.

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

    Java simply doesn't need the star and parenthesis.

    0 讨论(0)
  • 2020-12-23 09:20

    That's a funny Question. In java you can say int[] a;, as well as int a[];.
    From this perspective, in order to get the same result just need to move the []
    and write public int[] get() {.
    Still looks like the code came from an obfuscator...

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-23 09:26

    java's syntax allows for the following:

    int[] intArr = new int[0];
    

    and also

    int intArr[] = new int[0];
    

    which looks more fmiliar coming from the c-style syntax.

    so too, with a function, the name can come before or after the [], and the type is still int[]

    0 讨论(0)
提交回复
热议问题