Why is NetBeans warning 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); } } 

He complains about line 5, saying:

 Confusing primitive array passed to vararg method 

but as far as I ( and others on SO ) know, int... matches int[] . This works if it is not a primitive type, such as String , but not for 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 

After examining the NetBeans tooltip settings, I find that this says the following:

The simplest array passed to the variable-argument method will not be unpacked, and its elements will not be considered as variable-length argument elements in the called method. Instead, the array will be passed as a separate element.

However, when I run the file (since this is just a warning, not an error), I get exactly the expected result:

 1 2 3 4 5 

So why do I like NetBeans to pass my own array to the varargs method?

+5
source share
1 answer

This is 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); } } } 

Exit:

 [ I@15db9742 // on my machine 

Compared to 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); } } } 

Conclusion:

 1 2 3 4 5 

Note that in my examples the signature is prints() . It accepts Object... rather than int... NetBeans is trying to warn you that something โ€œstrangeโ€ (unexpected) may happen, but it erroneously reports that prints(int...) can do something โ€œunexpectedโ€.

+6
source

Source: https://habr.com/ru/post/1200769/


All Articles