Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NetBeans warn about passing int[] to vararg?

Why does the NetBeans precompiler give a warning for this?

public class PrimitiveVarArgs
{
    public static void main(String[] args)
    {
        int[] ints = new int[]{1, 2, 3, 4, 5};
        prints(ints);
    }

    static void prints(int... ints)
    {
        for(int i : ints)
            System.out.println(i);
    }
}

It complains about line 5, saying:

Confusing primitive array passed to vararg method

but as far as I (and others on SO) know, int... is the same as int[]. This works if it's a non-primitive type, like String, but not on primitives.

I can't even add this method:

void prints(int[] ints)
{
    for(int i : ints)
        System.out.println(i);
}

because the compiler says:

name clash: prints(int[]) and prints(int...) have the same erasure

cannot declare both prints(int[]) and prints(int...) in PrimitiveVarArgs

Upon looking into the NetBeans hints settings, I find it says this:

A primitive array passed to variable-argument method will not be unwrapped and its items will not be seen as items of the variable-length argument in the called method. Instead, the array will be passed as a single item.

However, when I run the file (since it's just a warning and not an error), I get exactly the output I expect:

1
2
3
4
5

so, why doesn't NetBeans like me passing a native array to a varargs method?

like image 319
Ky. Avatar asked Aug 20 '14 15:08

Ky.


1 Answers

It's a bug in NetBeans.

https://netbeans.org/bugzilla/show_bug.cgi?id=242627

Consider the following code:

public class Test {
    public static void main(String[] args) {
        int[] ints = new int[]{1, 2, 3, 4, 5};
        prints(ints);
    }

    static void prints(Object... ints) {
        for(Object i : ints) {
            System.out.println(i);
        }
    }
}

Output:

[I@15db9742 // on my machine

Versus this code:

public class Test {
    public static void main(String[] args) {
        Integer[] ints = new Integer[]{1, 2, 3, 4, 5};
        prints(ints);
    }

    static void prints(Object... ints) {
        for(Object i : ints) {
            System.out.println(i);
        }
    }
}

Output:

1
2
3
4
5

Notice in my examples the signature of prints(). It accepts Object..., not int.... NetBeans is trying to warn you that something "strange" (unexpected) might happen, but erroneously reports that prints(int...) could do something "unexpected".

like image 134
jdphenix Avatar answered Nov 08 '22 11:11

jdphenix