突然发现java的可变参数重载是存在歧义的,只是不知道java内部是怎么处理的,特意做如下实验:
测试代码如下:
1 /** 2 * Created by ieayoio on 16-3-1. 3 */ 4 public class VarTest { 5 6 public static void aaa(int ...a){ 7 System.out.println("可变参数重载"); 8 } 9 10 public static void aaa(int a){ 11 System.out.println("非可变参数重载"); 12 } 13 public static void main(String[] args) { 14 15 } 16 }
1.在14行添加aaa();时运行结果为:
可变参数重载
Process finished with exit code 0
2.在14行添加aaa(111,111);时运行结果为:
可变参数重载
Process finished with exit code 0
3.在14行添加aaa(111);时运行结果为:
非可变参数重载
Process finished with exit code 0
4.将代码改为以下:
1 /** 2 * Created by ieayoio on 16-3-1. 3 */ 4 public class VarTest { 5 6 public static void aaa(int a){ 7 System.out.println("非可变参数重载"); 8 } 9 10 public static void aaa(int ...a){ 11 System.out.println("可变参数重载"); 12 } 13 14 public static void main(String[] args) { 15 aaa(111); 16 } 17 }
结果依然为:
非可变参数重载
Process finished with exit code 0
结论:当使用可变参数重载方法时,java内部会优先使用非可变参数方法去执行程序
原文链接:http://www.cnblogs.com/ieayoio/p/5231751.html
时间: 2024-10-10 09:23:52