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? 

  

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM