一、测试代码
packagecom.demo;public classInterview {public static void test(inti){
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 voidmain(String[] args) {//TODO Auto-generated method stub
test();
test(1,2,3);
test(10);
test(new int[]{1});
}
}
二、输出结果
call the test(int... ary)0call the test(int... ary)3call the test(inti)
call the test(int... ary)1
三、浅析
1、可变参数的实际上调用过程实际上是将参数组织成一个数组,然后再出入该数组作为形参调用方法。
例如test(1,2,3)的执行过程为:
0: iconst_31: newarray int
3: dup4: iconst_05: iconst_16: iastore7: dup8: iconst_19: iconst_210: iastore11: dup12: iconst_213: iconst_314: iastore15: 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、数量不同:数组形式的形参可以有任意多个,但是可变长度的形参最多只能有一个。
联系:
变长度的形参本质上就是一个数组形参,因此调用一个可变长度形参的方法是,既可以传入多个参数,又可以直接传入数组参数。