Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, why is the call foo() not ambigious given 2 varags methods foo(int... ints) and foo(Object... objects)?

If I declare just the 2 varargs methods as follows:

public void foo(String... strings) {
    System.out.println("Foo with Strings");
}

and

public void foo(int... ints) {
    System.out.println("Foo with ints");
}

and then have the code:

foo();

this is a compiler error due to the ambiguity as expected.

However if I have just the following 2 versions of foo:

public void foo(Object... objects) {
    System.out.println("Foo with Objects");
}

and

public void foo(int... ints) {
    System.out.println("Foo with ints");
}

then the code

foo();

calls the ints version of the method. Can anyone explain why the second example isn't similarly ambiguous and why it resolves to the int method over the Object method. Thanks.

like image 527
mikej Avatar asked Jun 04 '09 15:06

mikej


2 Answers

If I recall properly from when I was preparing the scjp, in the first case you have 2 arguments with no relation between them, so the compiler can't choose one.

In the second, with boxing enabled (1.5+), int can be Integer which is a subset of Object, and the compiler, in case of conflict, will always use the most specific definition. So Integer (int) is prioritized.

like image 130
Pere Villega Avatar answered Nov 05 '22 19:11

Pere Villega


Java will always use the closest type possible, so when you pass ints into the method, if you didn't have the int... method, it would autobox them into Integers and use Object.... Since there is an int... method, Java will use that first. This is a choice in the Java compiler design.

like image 41
stevedbrown Avatar answered Nov 05 '22 19:11

stevedbrown