This question already has an answer here:
-
Can I pass an array as arguments to a method with variable arguments in Java?
5 answers
-
Java, 3 dots in parameters
9 answers
I am wondering how the parameter of ...
works in Java. For example:
public void method1(boolean... arguments)
{
//...
}
Is this like an array
? How I should access the parameter?
Its called Variable arguments or in short var-args, introduced in Java 1.5.
The advantage is you can pass any number of arguments while calling the method.
For instance:
public void method1(boolean... arguments) throws Exception {
for(boolean b: arguments){ // iterate over the var-args to get the arguments.
System.out.println(b);
}
}
The above method can accept all the below method calls.
method1(true);
method1(true, false);
method1(true, false, false);
As per other answer, it's a "varargs" parameter. Which is an array.
What many people don't realise is two important points:
- you may call the method with no parameters:
method1();
- when you do, the parameter is an empty array
Many people assume it will be null if you specify no parameters, but null checking is unnecessary.
You can force a null to be passed by calling it like this:
method1((boolean[])null);
But I say if someone does this, let it explode.