Java變長參數

來源:互聯網
上載者:User

在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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.