Java学习-方法05可变参数

可变参数

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

说白了就是可以传递多个同类型参数被称作可变参数。

package com.method.www;

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

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

运行结果

1
2
3
4
5
6

Process finished with exit code 0
package com.method.www;

public class Demo08 {
    public static void main(String[] args) {
        // 调用可变参数方法
        printMax(34,3,3,2,56.5);
        printMax(new double[]{1,2,3});
        
    }
    
    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:56.5
The max value is:3.0

Process finished with exit code 0
posted on 2025-06-16 22:29  burgess0x  阅读(14)  评论(0)    收藏  举报