Home > Enterprise >  In Java why is this syntax valid and this isn't?
In Java why is this syntax valid and this isn't?

Time:03-21

I understand that both of these are valid and mean the exact same thing:

Preferred:

void foo(int[] bar){
    // do something 
}

Not preferred:

void foo(int bar[]){
    // do something
}

What I don't understand is, following the same logic as above, why is this not valid?

void foo(int... bar[]){
    // do something 
}

But this is:

void foo(int[]... bar){
    // do something 
}

CodePudding user response:

Let's start with int bar[] versus int[] bar. The former is some syntactic sugar included in the original Java 1.0 for programmers transitioning from C or C . It is a bit of a "wart" on the Java syntax ... and most people now think it was a mistake to support it in the first place. And you are discouraged from using it by the spec itself, tutorials, books and ... Java style checkers.

So later in the evolution of Java (in Java 5) they added the ... syntax to support "varargs" functionality in method calls. Nice. But they didn't include support for the syntactic wart.

Why?

  • We weren't in the room when the decisions were made ... so we don't really know why.
  • Because the original wart was a bad idea
  • Because C / C don't support varargs that way, so it wouldn't help the transitioners.
  • Because int... bar[] is visually ambiguous1. Is it a "varags of arrays of int" or an "array of varargs of int"? Even C and C will not allow you to write int[] bar[], which is roughly what this maps to.
  • Because (frankly) void foo(int... bar[]) looks nasty.

1 - Maybe not actually ambiguous, since the "array of varargs of int" interpretation doesn't make sense. However, that is not going to avoid the confusion that the hypothetical syntax would cause. Best to avoid the problem ... like they did.

CodePudding user response:

In Java, its true that you can declare the array in 2 forms like

int[] arr;

or

int arr[];

The second one is usually not preferred as the brackets identify the array type and should appear with the type designation. In simple words, you can follow the convention of

type variable; 

form along all of your code with the first model of array usage.

Now coming to the question, this is exactly the reason the usage of varargs in the form of int... arr[] is not supported. The varargs specify the arbitrary count nature of the specific type.

So with type spec int... it means arbitrary count of integer values, and int[]... means arbitrary number of integer arrays. varargs supports a variable to be used as its a type and not array. So int... arr[] is an error.

  • Related