Java: the reference to .. is ambiguous, and the method1 and method2 in ... match

I came across the same code:

    public class Devk{
        public static void tMeth(Integer... i){
          System.out.print("A");
        }
        public static void tMeth(int... i){
          System.out.print("B");
        }
        public static void main(String args[]){
          tMeth(Integer.valueOf("7"));//compile error
          tMeth(new int[2]); //returns B
          tMeth(new Integer[2]); //returns A
        }

  }

after the call, I see

java: reference to tMeth is ambiguous, both method tMeth(java.lang.Integer...) in GenericsTest.Test1 and method tMeth(int...) in GenericsTest.Test1 match

The method Integer.valueOf("7")returns an integer shell. I expect to see Ain the console.

Who can explain this behavior and provide a general rule for this?

PS

public static void tMeth(Integer i){
    System.out.print("A");
}
public static void tMeth(int i){
    System.out.print("B");
}
public static void main(String args[]){
    tMeth(1); //returns B
    tMeth(new Integer(1)); //returns A
}
+4
source share
4 answers

When compiling a method call, the compiler searches for the appropriate method in the following order:

  • Try to find a method without autoboxing / unboxing or varargs.
  • If the method is not found, see if the method matches using autoboxing / unboxing.
  • , , , varargs, autoboxing/unboxing.

(3) . , .

, . , , (, String , Object, int , long).

int Integer ; (1) (2) , , , foo(int) foo(Integer).

, , , , .

JLS

+6

Java , Java -.

Java - - . "int" , "Integer" "Integer" , "int". Java .

, .

: http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

0

Integer ( Double, Byte, Float, Long ..) .

int, - Integer, Java 5 - , int Integer - ( Integer int, NullPointerException, null).

-2

- , "Autoboxing" java, . - int, - - Integer. 7 7, 7, .

Since the compiler will pass the primitive value to the arguments matching the primitive and the shell type (and vice versa for the wrapper type), you do not actually overload the methods, but duplicate them.

-2
source

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


All Articles