1. 程式人生 > >java中重載變長參數方法

java中重載變長參數方法

變參 style eth tor 多個 col 變長參數 形參 out

一、測試代碼

package com.demo;
public class Interview {
    public static void test(int i){
        System.out.println("call the test(int i)");
    }
    public static void test(int... ary){
        System.out.println("call the test(int... ary)");
        System.out.println(ary.length);
    }
    public static
void main(String[] args) { // TODO Auto-generated method stub test(); test(1,2,3); test(10); test(new int[]{1}); } }

二、輸出結果

call the test(int... ary)
0
call the test(int... ary)
3
call the test(int i)
call the test(int... ary)
1

三、淺析

1、可變參數的實際上調用過程實際上是將參數組織成一個數組,然後再出入該數組作為形參調用方法。

例如test(1,2,3)的執行過程為:

       0: iconst_3
       1: newarray       int
       3: dup
       4: iconst_0
       5: iconst_1
       6: iastore
       7: dup
       8: iconst_1
       9: iconst_2
      10: iastore
      11: dup
      12: iconst_2
      13: iconst_3
      14: iastore
      15: invokestatic  #41                 //
Method test:([I)V

從newarray指令可以看出就是組織成數組的過程。
2、test(int i)方法被重載了一個可變長度參數test(int... ary)

那麽

        test();//相當於執行test(new int[0])
        test(1,2,3);////相當於執行test(new int[]{1,2,3})

3、test(10)調用了第一個方法,說明在同時定義了test(int i)和test(int... ary)的情況下,如果只傳入一個參數:test(10),則test(int i)會被調用。

那麽在傳入一個參數的情況下,如何調用test(int... ary)呢?可以通過test(new int[]{1});的方式來調用。

四、數組形參和可變長度的形參的區別與聯系

區別:

1、出現的位置不同:數組形式的形參可以出現形參的任意位置,但是可變長度的形參只能出現在形參列表的最後。

2、數量不同:數組形式的形參可以有任意多個,但是可變長度的形參最多只能有一個。

聯系:

變長度的形參本質上就是一個數組形參,因此調用一個可變長度形參的方法是,既可以傳入多個參數,又可以直接傳入數組參數。

轉載請註明來源:http://www.cnblogs.com/qcblog/p/7668080.html

java中重載變長參數方法