该方法对于错误类型不明确

The method is ambiguous for the type Error

我试图了解 JAVA 中的重载是如何工作的,并试图掌握在 JAVA 中加宽、自动装箱和可变参数情况下应用的各种重载规则。我无法理解在以下情况下发生了什么:

 package package1;

 public class JustAClass {
     public static void add(int a, long b) {
         System.out.println("all primitives");
     }

   //public static void add(Integer a, long b) {
   //     System.out.println("Wraper int, primitive long");
   //}

     public static void add(int a, Long b) {
         System.out.println("Primitive int, Wrapper long");
     }

     public static void add(Integer a, Long b){
         System.out.println("All wrapper");
     }

     public static void main(String[] args) {
        int a = 10;
        Integer b = 10;
        long c = 9;
        Long d = 9l;

        add(a,c);
        add(a,d);
        add(b,c);
        add(b,d);
 }

}

此时,我在第三次调用 add 方法时遇到编译错误 The method is ambiguous for the type Error 。 为什么会这样?确定哪个方法调用有效的规则是什么?在下面的案例中到底发生了什么? 我觉得 fourth 重载的 add 方法应该可以工作。请帮助我理解这背后的概念。

方法重载解析有 3 个阶段。第一阶段不执行 auto-boxing/unboxing,这意味着需要传递参数的 boxing/unboxing 以匹配 add 的一个重载版本的方法只有在没有匹配时才会被考虑发现不需要 boxing/unboxing。这就是为什么您的 3 个调用(只有一个完全匹配)起作用的原因。关于add(b,c);,请看下面为什么不明确。

   add(a,c); // exact match to add(int a, long b)
   add(a,d); // exact match to add(int a, Long b)
   add(b,c); // there is no exact match, so at least one of the passed parameters must
             // be boxed or unboxed. However, by unboxing b to int or boxing 
             // c to Long, each of the three add methods can match, and the 
             // compiler doesn't know which one to prefer
   add(b,d); // exact match to add(Integer a, Long b)