Legacy array notation not allowed on variable parameter
I'm asking this out of curiosity as I didn't find a question about this particular compilation error on StackOverflow:
Legacy array notation not allowed on arity variable parameter
I came across a deprecated notation when I saw some code containing a signature like this:
private void a(int ints[]){/*...*/}
So, I played around for a bit until I ran into a compile error in the following samples.
// this method compiles as expected
private void method1(int[][] ints){ /*...*/ }
// this too
private void method2(int[]... ints){ /*...*/ }
// this does to, but makes use of legacy array notation
private void method3(int ints[][]){ /*...*/ }
// this still does, even when mixing up the notations
private void method4(int[] ints[]){ /*...*/ }
// this however fails to compile
private void method5(int... ints[]){ /*...*/ }
Is there a specific reason that the language designer decided to implement it this way? Don't allow varargs with array notation?
NOTE . I understand the convention
source to share
I don't know why they chose to do this *, however I would just like to confirm that this is a formal part of the specification and is entirely intended to create a compile-time error:
It is a compile-time error to use mixed array notation ( ยง10.2 ) for the arity variable parameter.
From JLS 8.4.1
* this question will be opinion based, as no one other than the developers of the Java language could tell you. If I was thinking, it's probably because allowing multiple notations in the first place was kind of a bad idea.
source to share
int[] a
, int a[]
- one and the same,
so 1, 3 and 4 are equivalent.
In 2, you basically say "I want varargs of type int []"
so it can be called like method2(new int[]{},new int[]{})
.
At 5, int..
tells the compiler that it is a vararg of type int
, and the parameter name is taken as ints[]
, which is an invalid variable name.
source to share