Java之可变参数方法使用说明

代码:

package test_demo;

/*
* 可变参数函数说明
* 传入指定数据类型的数组
* 优先匹配固定长度函数
* */

public class VarArgsDemo {

    //  可变参数函数
    public void printFn(String... args) {
        for (String s : args) {
            System.out.print(s + " ");
        }
        System.out.println();
    }

    //  优先匹配固定长度函数
    public void printFn(String s) {
        System.out.print("test!\n");

    }

    //  一个固定参数,其它可变参数函数
    public void printMore(String str, String... args) {
        System.out.println(str);
        for (String s : args) {
            System.out.print(s + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        VarArgsDemo obj = new VarArgsDemo();
        String str = "hello!";
        String[] strs = {"hello!", "Good!", "what?"};
        //  优先匹配固定长度函数
        obj.printFn(str);
        //  可变参数函数
        obj.printFn("hello!", "Good!");
        obj.printFn(strs);
        //  一个固定参数,其它可变参数函数
        obj.printMore("------", strs);

    }

}

 

执行结果:

test!
hello! Good! 
hello! Good! what? 
------
hello! Good! what? 

  

  

posted @ 2017-11-10 15:15  星瑞  阅读(2255)  评论(0编辑  收藏  举报