参数中的 3 个点是什么?/什么是可变参数 (...) 参数?

2022-01-21 00:00:00 arrays arguments methods parameters java

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

相关文章