bug with varargs and overloading?

Posted by pstanton on Stack Overflow See other posts from Stack Overflow or by pstanton
Published on 2010-03-26T05:28:15Z Indexed on 2010/03/26 5:33 UTC
Read the original article Hit count: 603

Filed under:
|
|

There seems to be a bug in the Java varargs implementation. Java can't distinguish the appropriate type when a method is overloaded with different types of vararg parameters.

It gives me an error The method ... is ambiguous for the type ...

Consider the following code:

public class Test
{
    public static void main(String[] args) throws Throwable
    {
        doit(new int[]{1, 2}); // <- no problem
        doit(new double[]{1.2, 2.2}); // <- no problem
        doit(1.2f, 2.2f); // <- no problem
        doit(1.2d, 2.2d); // <- no problem
        doit(1, 2); // <- The method doit(double[]) is ambiguous for the type Test
    }

    public static void doit(double... ds)
    {
        System.out.println("doubles");
    }

    public static void doit(int... is)
    {
        System.out.println("ints");
    }
}

the docs say: "Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called."

however they don't mention this error, and it's not the programmers that are finding it difficult, it's the compiler.

thoughts?

© Stack Overflow or respective owner

Related posts about java

Related posts about overloading