When I run this code:
class Test {
public static void main(String[] args) throws Exception {
someMethod(new int[] {1, 2, 3});
}
static void someMethod(Object obj) {
System.out.println("Single object given: " + obj);
}
static void someMethod(Object[] objs) {
System.out.println("Multiple objects given: " + Arrays.toString(objs));
}
}
I get ouput in which someMethod(Object[] objs)
is selected for int[]
:
Single object given: [I@140e19d
I faced with such behaviour when tried to log some message as this:
logger.log(Level.INFO, "param1: {0}, param2: {1}", new int[] {1, 2});
which outputs:
...
INFO: param1: [I@103dbd3, param2: {1}
So why it is selected Object instead of Object[] as method argument for primitive arrays?
Because an int[]
isn't an Object[]
- it's as simple as that. An element of an Object[]
has to be a reference - and an element of an int[]
is not a reference.
JLS section 4.10.3 talks about the subtype relationships for arrays - in particular:
If
S
andT
are both reference types, thenS[] >1 T[]
iffS >1 T
.
See more on this question at Stackoverflow