10

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.

mikej
  • 65,295
  • 17
  • 152
  • 131
  • 1
    You haven't shown the calls to foo, without which this question is hard to answer. – Jon Skeet Jun 04 '09 at 15:49
  • 1
    Jon, the call to foo() is literally foo() i.e. with zero arguments. I will edit the question to make this clearer. – mikej Jun 04 '09 at 15:52
  • With *just* int... and object..., this compiles for me. With String... and int... (but not Object...) it doesn't. Could you check the question please? – Jon Skeet Jun 04 '09 at 16:01
  • 1
    @Jon Skeet - That is the expected behaviour and what he claims in his question. But WHY does the int and object version work and why does it choose int? – willcodejavaforfood Jun 04 '09 at 16:05
  • 1
    @Jon I think that is precisely what is supposed to happen and that's why the question is being asked. – Vincent Ramdhanie Jun 04 '09 at 16:06

2 Answers2

29

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.

Pere Villega
  • 16,429
  • 5
  • 63
  • 100
  • 6
    This is correct. From the JLS ... 15.12.2.5 Choosing the Most Specific Method http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.2.5 – justinhj Jun 04 '09 at 16:00
4

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.

stevedbrown
  • 8,862
  • 8
  • 43
  • 58