1. 程式人生 > >Java中的可變引數使用

Java中的可變引數使用

1.可變引數的定義

從JDK1.5之後,java就提供了變長引數(variable arguments,varargs)。我們在定義方法的時候,可以使用不確定個數的引數。對於同一個方法,也可以通過不確定引數個數的方式進行過載。首先來看個最簡單的例子:

public void printArray(String... args) {
    for(int i=0; i<args.length; i++) {
        System.out.print(args[i] + " ");
    }
}

在main方法裡呼叫此方法,例如:

printArray("hello"
,"world")
;

這個時候控制檯會打印出hello world!以上就是可變引數最簡單的應用方式。

2.與固定引數方法的比較

如果某一方法被呼叫的時候,既能與固定引數個數的方法match,也能與被過載的有可變引數的方法match,那麼優先呼叫固定引數個數的方法。

public class MultiPrameters {

    public void printArray(String... args) {
        for(int i=0; i<args.length; i++) {
            System.out.print(args[i] + " "
); } } public void printArray(String rawString) { System.out.println("only one string!"); } public static void main(String[] args) { MultiPrameters mul = new MultiPrameters(); mul.printArray("hello"); mul.printArray("hello","world"); } }

將上面的程式碼run起來以後,控制檯輸出如下:

only one string!
hello world 

3.每個方法最多一個變長引數,並且該引數的位置是方法的的最後

public void print(String... args,Int num){}

public void print(String... args,Int... nums){}

以上兩種寫法,都是錯誤的!
這裡寫圖片描述

IDE裡會直接提示你:Vararg paramter must be the last in the list!

4.注意不能讓呼叫的方法可以與兩個可變引數匹配

理解起來也不是很複雜,大家看如下示例程式碼

這裡寫圖片描述

IDE裡直接報錯,ambiguous method call both! 很明顯,main方法呼叫的時候不知道呼叫哪個printArray方法!所以我們在實際編碼過程中,避免帶有變長引數方法的過載