public class Foo {
public static void main(String[] args) throws Exception {
foo(new int[]{1,2,3});
}
static void foo(Object o) {
System.out.println("object");
}
static void foo(Object[] o) {
System.out.println("array");
}
}
Why does this print "object" instead of "array"?
The simple answer is that int[]
isn't a subtype of Object[]
because int
isn't a subtype of Object
.
Java's type hierarchy does not have a supremum, so unfortunately it's impossible to write a method with a parameter that can be any type of array. This is why, if you look at APIs like java.util.Arrays, you'll see a lot of methods that are repeated for byte[]
, char[]
, double[]
, float[]
, int[]
, long[]
, short[]
, and Object[]
.