Reputation: 507095
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};
}
}
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!
Can someone please help me understand what it means? Is it an array of functions?
Upvotes: 125
Views: 8035
Reputation: 422076
It's a method that returns an int[]
.
The declaration of a method that returns an array is allowed to place some or all of the bracket pairs that denote the array type after the formal parameter list. This syntax is supported for compatibility with early versions of the Java programming language. It is very strongly recommended that this syntax is not used in new code.
Upvotes: 114
Reputation: 52294
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.
Upvotes: 12
Reputation: 13728
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...
Upvotes: 22
Reputation: 45545
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[]
Upvotes: 5