Please regard the following lines of code:
public static void main(String[] args) {
foo(1,2,3);
System.out.println("-------------------------------------");
foo(new Integer(1), new Integer(2), new Integer(3));
System.out.println("-------------------------------------");
foo(new Integer[]{1,2,3});
System.out.println("-------------------------------------");
foo(new Integer[] {new Integer(1), new Integer(2), new Integer(3)});
}
public static void foo(Object... bar) {
System.out.println("bar instanceof Integer[]:\t" + (bar instanceof Integer[]));
System.out.println("bar[0] instanceof Integer:\t" + (bar[0] instanceof Integer));
System.out.println("bar.getClass().isArray():\t" + bar.getClass().isArray());
}
The output of this code snippet is:
bar instanceof Integer[]: false
bar[0] instanceof Integer: true
bar.getClass().isArray(): true
-------------------------------------
bar instanceof Integer[]: false
bar[0] instanceof Integer: true
bar.getClass().isArray(): true
-------------------------------------
bar instanceof Integer[]: true
bar[0] instanceof Integer: true
bar.getClass().isArray(): true
-------------------------------------
bar instanceof Integer[]: true
bar[0] instanceof Integer: true
bar.getClass().isArray(): true
And this confuses me quite a bit! I don't understand why in case of foo(1,2,3)
the term bar instanceof Integer[]
is false.
If in these cases bar is not an instance of Integer[]
what else is it an instance of?
Object[]
and not anInteger[]
. For the last two you are explicity passing anInteger[]
, so your condition will be true now. – Blasfoo(new int[]{1,2,3});
. The result will go from confusing to weird! – Kastint[]
will be interpreted as a single object instead of wrapping all theint
s! Nice addition! – Inherence