java 可变参数

可变参数?

可变参数允许调用参数数量不同的方法。请看下面例子中的求和方法。此方法可以调用1个int参数,或2个int参数,或多个int参数。

  1. //int(type) followed ... (three dot's) is syntax of a variable argument.  
  2.    public int sum(int... numbers) { 
  3.        //inside the method a variable argument is similar to an array. 
  4.        //number can be treated as if it is declared as int[] numbers; 
  5.        int sum = 0; 
  6.        for (int number: numbers) { 
  7.            sum += number; 
  8.        } 
  9.        return sum
  10.    } 
  11.  
  12.    public static void main(String[] args) { 
  13.        VariableArgumentExamples example = new VariableArgumentExamples(); 
  14.        //3 Arguments 
  15.        System.out.println(example.sum(1, 4, 5));//10 
  16.        //4 Arguments 
  17.        System.out.println(example.sum(1, 4, 5, 20));//30 
  18.        //0 Arguments 
  19.        System.out.println(example.sum());//0 
  20.    }  
原文地址:https://www.cnblogs.com/hzcya1995/p/13317638.html