Java:可变参数

  • JDK1.5开始,Java支持传递同类型的可变参数给一个方法。

  • 在方法声明中,在指定参数类型后加一个省略号(...)。

  • 一个方法中只能指定一个可变参数,它必须是方法的最后一个参数。任何普通的参数必须在它之前声明。

  • 可变参数的本质就是数组。


package com.jiemyx.method;

public class Demo04 {
    public static void main(String[] args) {
        Demo04 demo04 = new Demo04();
        demo04.test(1,2,3,4,5);
    }

    public void test(int... i){
        System.out.println(i[0]);
        System.out.println(i[1]);
        System.out.println(i[3]);
    }

    //错误演示,可变参数必须在最后
    //public void test(int... i,double d){}

    //正确演示
    public void test(double d2,int... i){}

}

运行结果:

1
2
4


package com.jiemyx.method;

public class Demo05 {
    public static void main(String[] args) {
        //调用可变参数的方法
        printMax(1,3,5.6,7,8);
        printMax(new double[]{1,3,5});
    }

    public static void printMax(double... numbers){
        if (numbers.length == 0){
            System.out.println("No argument passed");
            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 8.0
The max value is 5.0

posted @ 2021-03-27 21:18  杰myx  阅读(66)  评论(0)    收藏  举报