请看下面的代码行:
这段代码的输出结果是:
这让我有点困惑!我不明白为什么在
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());
}
这段代码的输出结果是:
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
这让我有点困惑!我不明白为什么在
foo(1,2,3)
的情况下,bar instanceof Integer[]
是假的。
如果在这些情况下 bar 不是 Integer[]
的实例,那它还能是什么实例呢?
Object[]
而不是Integer[]
。对于最后两个,您明确地传递了Integer[]
,因此您的条件现在将为真。 - SomeJavaGuyfoo(new int[]{1,2,3});
的测试。结果将从令人困惑变得奇怪! - Liiint[]
将被解释为单个对象,而不是包装所有的int
!很棒的添加! - ParkerHalo