Fork me on Gitee

可变参数

可变参数

  • 在JDK1.5开始,JAVA支持传递同类型的可变参数给一个方法。
  • 在方法的声明中,在指定参数类型后加一个省略号(...)。
  • 一个方法中只能指定一个可变参数,它必须是方法的最后一个参数。任何普通的参数必须在它之前声明!
typeName... parameterName

实例

package com.singer.method;

public class Demo07 {
    public static void main(String[] args) {
        // 调用可变参数的方法
        printMax(20,56,50,85,43);
        printMax(new double[]{1,2,3});
    }

    //可变参数
    public static void printMax(double... numbers){
        if (numbers.length == 0){
            System.out.println("NO argument passde!");
            return;
        }
        double result= numbers[0];
        //排序
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i]>result){
                result = numbers[i];
            }
            System.out.println("The max value is " + result);
        }
    }
}

以上实例编译运行结果如下:

The max value is 56.0
The max value is 56.0
The max value is 85.0
The max value is 85.0
The max value is 2.0
The max value is 3.0
posted @ 2020-12-09 22:59  ZHANG_Singerw  阅读(41)  评论(0编辑  收藏  举报