Suppose this code:
public class Test{
public static void main(String[] args) {
Test.testInt(new int[]{2,3});
Test.testInteger(new Integer[]{2,3});
}
public static void testInt(Object... elements){
System.out.println(elements[0] instanceof int[]);
}
public static void testInteger(Object... elements){
System.out.println(elements[0] instanceof Integer);
}
}
In both cases, one expected to have a one-dimensional array which contains 2 and 3.
So the expected output should be at first sight:
false
true
Surprise! the real output is:
true
true
UPDATE TO THIS POST:
Actually, it is not a good question since I haven’t realized that this case is in accordance with the Var-args rules.
To sum up, an int[] array cannot be autoboxed to Integer[] even when a Var-args is the argument; there’s no exceptional treatment.
You can’t autobox a primitive array to an “wrapper” array: an array is a totally different type! There are some quite clear use cases for autoboxing primitives. Those use cases don’t exist for arrays.
Your method signature asks for at least one
Object, and you supplied one:int[]. Your method signature also allows you to provide an array, which you do withInteger[].It’s also worth pointing out that all varargs methods can be invoked with arrays of the parameter type, which is what you’re doing with
Integer. Sinceintisn’t anObject, your compiler treats the array as anObject.