Primary vararg parameters when overloading a method

Primitives reappear, breaking the rules that I learned earlier. Well, not technically primitive, but made up of them.

I found out that whenever there is no method more specific than resting, a compile-time error occurs, as happens here.

public static void caller(){
    z5();  // Error. Neither Integer, nor String is more specific
    z5(null);  // Error for the same reason
}
public static void z5(Integer...integers){
    System.out.println("Integer z5 called");
}
public static void z5(String...strings){
    System.out.println("String z5 called");
}

Now primitives appear in the picture.

public static void caller(){
    z1(null);  // Error cuz [I, [J, [F all are subclass of Object.
    z1();  // SURPRISINGLY works and calls the int one. WHY?
}
public static void z1(int...integers){
    System.out.println("int z1 called");
}
public static void z1(long...longs){
    System.out.println("long z1 called");
}
public static void z1(float...floats){
    System.out.println("float z1 called");
}

Compilation time errors are expected here.

public static void caller(){
    z1(null);  // Error
    z1();  // Error
}
public static void z1(int...integers){
    System.out.println("int z1 called");
}
public static void z1(boolean...bools){
    System.out.println("bool z1 called");
}

Now my question is: int [], float [] or any array of primitives are not primitive types. Why are they handled differently than other reference types?

- UPDATE -

@ john16384 You don’t think I read your “Possible duplicate” of Varargs in method overloading in Java

var-args . , , OP , jdk 7.

, (int... is) (float... fs), (Integer... is) (Float...fs), (int... is) (boolean... bool)

+6
1

JLS varargs, :

15.12.2.5.

- , . Java , .

, , , , , , . , (§15.27.1) (§15.12.2.4), .

, . , int... , long..., , , .

, . int... ( byte... !).

public static void main(String[] args) {
    bla();
}

private static void bla(long... x) {}
private static void bla(int... x) {}
private static void bla(short... x) {}
private static void bla(byte... x) {}   // <-- calls this one

, boolean..., , , , , , .

+1

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


All Articles