Java中的可變參數

來源:互聯網
上載者:User

標籤:html5   springmvc   mybatis   bootstrap   shiro   

Java在1.5之後允許方法使用可變參數,可變參數的好處在於:它允許傳遞0個或者多個參數。比如原來有一段代碼下載如下: 

Java代碼  650) this.width=650;" class="star" src="http://yizhenn.iteye.com/images/icon_star.png" alt="收藏代碼" style="border:0px;" />

  1. public class Test {    

  2.     public static void main(String[] args) {    

  3.         test();    

  4.         test(new String[]{"a"});    

  5.         test(new String[]{"a", "b"});    

  6.     }    

  7.     

  8.     private static void test() {    

  9.         System.out.println(“[]”);    

  10.     }    

  11.     

  12.     private static void test(String[] args) {    

  13.         System.out.println(Arrays.toString(args));    

  14.     }    

  15. }    


使用可變參數之後的代碼下載如下: 

Java代碼  650) this.width=650;" class="star" src="http://yizhenn.iteye.com/images/icon_star.png" alt="收藏代碼" style="border:0px;" />

  1. public class Test {    

  2.     public static void main(String[] args) {    

  3.         test();    

  4.         test(new String[]{"a"});    

  5.         test(new String[]{"a", "b"});    

  6.     }    

  7.     

  8.     private static void test(String... args) {    

  9.         System.out.println(Arrays.toString(args));    

  10.     }    

  11. }    


可見,可變參數的功能更加強大,語意包含的範圍更廣。 
我們知道,在Java中,除了8種基本類型之外一切都是類。那麼可變參數到底是個什麼類呢?來,用代碼下載驗證下! 

Java代碼  650) this.width=650;" class="star" src="http://yizhenn.iteye.com/images/icon_star.png" alt="收藏代碼" style="border:0px;" />

  1. public class Test {    

  2.     public static void main(String[] args) {    

  3.         whatClass();    

  4.         whatClass1();    

  5.     }    

  6.     

  7.     private static void whatClass(String... args) {    

  8.         System.out.println(args.getClass());    

  9.         System.out.println(new String[]{}.getClass());    

  10.     }    

  11.     

  12.     private static void whatClass1(int... args) {    

  13.         System.out.println(args.getClass());    

  14.         System.out.println(new int[]{}.getClass());    

  15.     }    

  16. }    


上面代碼的運行結果是: 
class [Ljava.lang.String;  
class [Ljava.lang.String;  
class [I  
class [I 


Java中的可變參數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.