What is the 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 the code with (Integer ... i) displayed a warning message, and the other executed correctly. But I can not 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 this code is run, a warning message is displayed.

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), the code ran fine.

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

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

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

And output display:

int array
+4
source share
3 answers

One important thing to keep in mind is that varargs are compiled to create and accept arrays. I.e

void test(Integer... i)

and

void test(Integer[] i)

- . ( . .) :

test(i1, i2, i3);

...

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

.

Integer..., test(null), , null , , Integer , null . , , test(new Integer[] { null }).

int..., test(null), null int, int . , null . test(new int[] { null }), ; test((int[])null). null int[], .

+7
test(null);
  • null Integer, Integer...
  • null Integer[], Integer
  • null int, int...
  • null int[], int
0

, null .

public static void test(Integer...i) Integer, Integer[]. , test(null);, , null . , Integer, Integer[]. .

public static void test(int...i) int, , int[], . null, , null int[] , , .

0

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


All Articles