Strange overload behavior using variable arguments with primitive types in java

It’s clear that I don’t have enough knowledge about how the functions of overloading, autoboxing and variables work.

So, here the program causes problems when there is involvement of primitive types.

public static void z(int a, Object...objects){
}
public static void z(Object...objects){
}
public static void main(String[] args) {
    z();    // no error
    z(4);   // Compile time Error : Ambiguous

    z2();               // No error
    z2(true, "sadas");  // Error

    // No problem with reference types
    z3();       // No error. String one called
    z3(5);      // No error. Object one called

    z4();       // Error
    z4(4);      // Error
    z4("asdas");    // Working properly
}
public static void z2(boolean b, Object...objects){
}
public static void z2(Object...objects){
}
public static void z3(String...objects){
    System.out.println("String one called");
}
public static void z3(Object...objects){
    System.out.println("Object one called");
}
public static void z4(int...objects){
    System.out.println("int z4 called");
}
public static void z4(Object...objects){
    System.out.println("Object z4 called");
}

Can someone explain why this is happening? I can happily use Integer, Boolean instead of int, boolean, but would really like to know the internal work behind it.

+4
source share
2 answers

, , .

z4:

  • z4() .
  • z4(4) , .
  • z4("asdas") , String int.

: :

(§15.12.2.2) arity. - , .

...

(§15.12.2.3) , arity. - , .

...

(§15.12.2.4) arity, .

, , *, z3(String...) , z3(Object...), z4(int...) z4(Object...) .

* (. )

+2

public static void z2(boolean b, Object... objects) {
    }

    public static void z2(Object... objects) {
    }

vararg, , .

java

,

, .

, ,

void z2(boolean b, Object... objects)
    public static void z2(Object... objects) 

.

,

    z2(true); 
    z2(true, "sadas"); 

public static void z2(boolean b, Object... objects) {
            }
Or
    public static void z2(Object... objects) {
    }

.

   public static void z2(boolean b, String... objects) {

        }
        public static void z2(String... objects) {
        }
z2(); // No error
z2(true, "sadas"); // No error

,

0

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


All Articles