Definition and usage of variable length parameter in java

  • 2020-05-19 04:55:21
  • OfStack

In JAVA, variable length parameters (Varargs) can be defined for a method to match multiple parameters of an uncertain number, with the definition of "..." Said. In fact, this is similar to passing an array to a method and using the same method as an array, as follows:


public void test(String... str){   
    for(String s : str){
      
    }
  }

The method is called in the same way as a normal call, except that it can be matched with zero or more arguments. As follows:


test();

test("lilei");

test("lilei","hanmeimei");

Several points should be noted in the process of use:

1. When calling, if the method with fixed parameters and variable length parameters can be matched at the same time, the method with fixed parameters will be matched first.

2. If you can match two methods with variable arguments at the same time, the compiler will report an error, because the compiler does not know which method to call.

3. A method can only have one variable parameter, and the variable parameter should be the last parameter.


Related articles: