The method is ambiguous for the type Error

I am trying to understand how overloading in JAVA works and trying to understand the different overload rules that apply in the case of extension, auto-blocking and varargs in JAVA. I can not understand what is happening in the following scenario:

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); } } 

At this point, I get a compilation error on the third call to the add method saying The method is ambiguous for the type Error . Why is this so? What are the rules for determining which method call will work? What exactly happens in the following case? I feel that the fourth overloaded add method should work. Please help me understand the concept of this.

+5
source share
1 answer

There are 3 stages of method resolution overloading. At the first stage, automatic boxing / unpacking is not performed, which means that methods that require boxing / unpacking the transferred parameters to correspond to one of the overloaded add versions will be taken into account only if no match is found, t boxing / unpacking is required. That's why 3 of your calls work that have one exact match. As for add(b,c); , see below why this is ambiguous.

  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) 
+6
source

Source: https://habr.com/ru/post/1239624/


All Articles