What are the 3 dots in parameters?/What is a variable arity (…) parameter? [duplicate]

↘锁芯ラ 提交于 2019-12-17 16:46:10

问题


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?


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/14739831/what-are-the-3-dots-in-parameters-what-is-a-variable-arity-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!