Use the Java mutable parameters example

  • 2020-04-01 03:16:09
  • OfStack

Java1.5 adds a new feature: variable parameters: for cases where the number of parameters is uncertain and the type is certain, Java treats variable parameters as an array. Note: the variable parameter must be in the last item. When there are more than one variable parameter, one must not be the last term, so only one variable parameter is supported. Because the number of parameters is variable, Java cannot tell whether the parameter passed in is the previous variable parameter or the next variable parameter when there are arguments of the same type following it, so it can only place the variable parameter in the last item.

Features of variable parameters:

1. Can only appear at the end of the parameter list;

2,... Between the variable type and the variable name, with or without a space;

3. When a variable-parameter method is called, the compiler implicitly creates an array for the variable-parameter and accesses the variable-parameter as an array in the method body.


public class Varable {
 public static void main(String [] args){
  System.out.println(add(2,3));
  System.out.println(add(2,3,5));
 }
 public static int add(int x,int ...args){
  int sum=x;
  for(int i=0;i<args.length;i++){
   sum+=args[i];
  }
  return sum;
 }
}


Sample code 2


public static void main(String[] args) {
T.test("1","2","3");
}
public static void test(String... ps){
System.out.println(ps.length);
for(String s : ps){
System.out.println(s);
}
} 

Ps up here is equivalent to a String array


Related articles: