Overload methods with var-args - combined with boxing and extension

When overloading methods that do not match the parameters, the JVM will always use the method with the smallest argument, which is wider than the parameter.

I confirmed this with the following two examples:

Extension: byte expanded to int

class ScjpTest{

    static void go(int x){System.out.println("In Int");}
    static void go(long x){System.out.println("In long");}

    public static void main (String[] args){

        byte b = 5;

        go(b);

    }

}

Boxing: int boxed to Integer

class ScjpTest{

    static void go(Integer x){System.out.println("In Int");}
    static void go(Long x){System.out.println("In Long");}

    public static void main (String[] args){

        int b = 5;

        go(b);

    }

}

Both of the above examples output "In Int", which is correct. I am confused though when the situation is related to var-args as shown in the following example

class ScjpTest{

    static void go(int... x){System.out.println("In Int");}
    static void go(long... x){System.out.println("In lInt");}

    public static void main (String[] args){

        byte b = 5;   //or even with:  int b = 5

        go(b);

    }

}

The above error causes an error:

ScjpTest.java:14: reference to go is ambiguous, both method go(int...) in ScjpTest and method go(long...) in ScjpTest match
                go(b);
                ^
1 error

Why does this not apply to the same rule as in the previous examples? those. expand byte to int since it is smallest than byte size?

+5
source share
3

var-args - :

foo(int ... arg) foo(int[] arg)

. String[] Object[]. . , long[] int[], byte.

+5

Java 7: "In Int" varargs. , . , Java , , , Java 6.

, , ( varargs). . , , Byte, Integer Long, ( , Number).

+1

AlexR, var-args - . (, byte[] short[] int[] long[] float[] double[] . , . :
  static void go(int... x){System.out.println("In Int");}
static void go(Long... x){System.out.println("In lInt");}

( int[] Long[] ) In Int.
SCJP, SCJP Sun Certified Programmer Java 6 Exam 310-065. var-args.

+1

All Articles