Java 可变参数

北城余情 提交于 2020-01-21 12:42:41

    Java(JDK > 1.5) 支持传递同类型的可变参数给一个方法。一个方法中只能指定一个可变参数,它必须是方法的最后一个参数,在指定参数类型后加一个省略号(...) 。

方法的可变参数的声明如下所示:

typeName... parameterName

实例:

public class Test {
    public static void main(String args[]) {
        // 调用可变参数的方法
        printMax("data", "number", "letter");
        printMax(new String[]{"happy", "fun", "lucky", "happiness"});
    }

    public static void printMax( String... lookup) {
        if (lookup.length == 0) {
            System.out.println("No argument passed");
            return;
        }

        String result = lookup[0];

        for (int i = 1; i <  lookup.length; i++){
            if (lookup[i].length() >  result.length()) {
                result = lookup[i];
            }
            else if(lookup[i].length() ==  result.length()){
                System.out.println(result + " and " + lookup[i] + " : Both strings are the same length");
            }        
        }
        System.out.println("The maximum field of \"lookup\" is : " + result);
    }
}

结果展示:

number and letter : Both strings are the same length
The maximum field of "lookup" is : number
happy and lucky : Both strings are the same length
The maximum field of "lookup" is : happiness

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!