在Java5中提供了變長參數,也就是在方法定義中可以使用個數不確定的參數,對於同一方法可以使用不同個數的參數調用,例如:print("hello");print("hello","lisi");print("hello","張三");下面介紹如何定義可變長參數以及如何使用可變長參數。
1、可變長參數方法的定義
使用...表示可變長參數,例如
print(String... args){
...
}
在具有可變長參數的方法中可以把參數當成數組使用,例如可以迴圈輸出所有的參數值。
print(String... args){
for(String temp:args)
System.out.println(temp);
}
2、可變長參數的方法的調用
調用的時候可以給出任意多個參數,例如:
print("hello");
print("hello","lisi");
print("hello","張三");
3、注意事項
3.1 在調用方法的時候,如果能夠和固定參數的方法匹配,也能夠與可變長參數的方法匹配,則選擇固定參數的方法。看下面代碼的輸出:
package ch6;
import static java.lang.System.out;
public class VarArgsTest {
public static void main(String[] args) {
VarArgsTest test = new VarArgsTest();
test.print("hello");
test.print("hello","zhangsan");
}
public void print(String... args){
for(int i=0;i<args.length;i++){
out.println(args[i]);
}
}
public void print(String test){
out.println("----------");
}
}
3.2 如果要調用的方法可以和兩個可變參數匹配,則出現錯誤,例如下面的代碼:
package ch6;
import static java.lang.System.out;
public class VarArgsTest {
public static void main(String[] args) {
VarArgsTest test = new VarArgsTest();
test.print("hello");
test.print("hello","zhangsan");
}
public void print(String... args){
for(int i=0;i<args.length;i++){
out.println(args[i]);
}
}
public void print(String test,String...args ){
out.println("----------");
}
}
對於上面的代碼,main方法中的兩個調用都不能編譯通過。
3.3 一個方法只能有一個可變長參數,並且這個可變長參數必須是該方法的最後一個參數
以下兩種方法定義都是錯誤的。
public void test(String... strings,ArrayList list){
}
public void test(String... strings,ArrayList... list){
}
下面是一個有陷阱的例子(例子來源http://topic.csdn.net/u/20090515/23/54cca7cb-f9a**84f-9a25-1be1ab447ec8.html),請寫出輸出結果:
public class TestVarargs{
public static void m(String[] ss){
for(int i=0; i <ss.length; i++){
System.out.println(ss[i]);
}
}
public static void m1(String s, String... ss){
for(int i=0; i <ss.length; i++){
System.out.println(ss[i]);
}
}
public static void main(String[]args){
String[] ss = {"aaa", "bbb", "ccc"};
m(ss);
m1("");
m1("aaa");
m1("aaa", "bbb");
}
}
完畢!
李緒成 CSDN Blog:http://blog.csdn.net/javaeeteacher
CSDN學生大本營:http://student.csdn.net/space.php?uid=124362
如果喜歡我的文章,就加我為好友:http://student.csdn.net/invite.php?u=124362&c=7be8ba2b6f3b6cc5