Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between varagrs using (int...i) and (Integer...i)

When I run this code with two different varargs (Integer...i) and (int...i), the output of code with (Integer...i) displayed warning message and the other was run correctly. But I cannot understand the different between them.

public static void test(Integer...i) {

    System.out.println("int array");
}

public static void main(String[] args) {
    test(null);
}

When run this code, warnings message display like that.

File.java:11: warning: non-varargs call of varargs method with inexact argument type for last parameter;
    test(null);
         ^cast to Integer for a varargs call

But when I change varargs (Integer...i) to(int...i), code was run perfectly.

public static void test(int...i) {

    System.out.println("int array");
}

public static void main(String[] args) {
    test(null);
}

And output display is:

int array
like image 514
Kum Kum Avatar asked Mar 09 '23 15:03

Kum Kum


1 Answers

One key thing to remember is that varargs are compiled to creating and accepting arrays. That is,

void test(Integer... i)

and

void test(Integer[] i)

are effectively the same thing. (Waves hands. There are some bookkeeping differences.) When you call it:

test(i1, i2, i3);

...the call is really

test(new Integer[] { i1, i2, i3 });

And that's the source of the issue here.

With Integer..., when you use test(null), you're saying you want to pass null as the first integer of what might be several, because Integer is an reference type and so null can match it. So you're passing an inexact type for the first entry in the array, like this test(new Integer[] { null }).

With int..., when you use test(null), the null can't be the first int because int is not a reference type. So the compiler determines that you're passing null as the array itself. You can't be trying to do test(new int[] { null }) because that would be invalid; so you must be doing test((int[])null). Since null is perfectly acceptable for an int[] parameter, the call compiles without warning.

like image 129
T.J. Crowder Avatar answered Apr 04 '23 23:04

T.J. Crowder