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