3

This code compiles and runs in Java 6 (IBM Java 6) but does not compile in Java 8 (IBM Java 8, and Eclipse's built-in compiler) :

public class App {
    public static void main(String[] args) {
        App app = new App();
        app.test(true, new Object());
    }

    void test(boolean b, Object... objects) {
    }

    void test(Object... objects) {
    }
}

The compilation error is:

The method test(boolean, Object[]) is ambiguous for the type App

I found this problem while migrating a real application from Java 6 to Java 8. This code looks ok to me as varargs methods are usualy used as a last resort when Java chooses among overloaded methods.

What is the problem here?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Alexey
  • 2,542
  • 4
  • 31
  • 53
  • Do you need the IBM Java version, or have you tried the Oracle version? – Tom Aug 30 '16 at 09:14
  • My Eclipse with Java 8 is fine with those declarations. – Alex K. Aug 30 '16 at 09:15
  • 1
    @AlexK. Mine is not. – shmosel Aug 30 '16 at 09:16
  • @Tom I did not try Oracle Java. – Alexey Aug 30 '16 at 09:17
  • The relevant section of the JLS is 15.12.2.5. Compare [Java 6](https://docs.oracle.com/javase/specs/jls/se6/html/expressions.html#15.12.2.5) and [Java 8](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.5). Whilst I can't point to the specifically relevant change, the wording has changed substantially. – Andy Turner Aug 30 '16 at 09:18
  • 7
    You'll find here the explanation : http://stackoverflow.com/questions/7689386/why-doesnt-autoboxing-overrule-varargs-when-using-method-overloading-in-java-7 – hasnae Aug 30 '16 at 09:23
  • Thanks, it is the answer to my question and a solution to my problem. – Alexey Aug 30 '16 at 19:51

1 Answers1

0

I think this is because of Object type. Compiler thinks that boolean parameter is a subclass of Object (maybe because of autoboxing?), so it treats it as another vararg.

Alexiy
  • 1,966
  • 16
  • 18