Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我能';t使用;instanceof";对于Int和Integer的比较数组?_Java_Arrays - Fatal编程技术网

Java 为什么我能';t使用;instanceof";对于Int和Integer的比较数组?

Java 为什么我能';t使用;instanceof";对于Int和Integer的比较数组?,java,arrays,Java,Arrays,为什么这段代码会抛出编译错误 Integer[] arr = new Integer[3]; if (arr instanceof Integer) { System.out.println("true"); } arr是一个对象,同时Integer是一个对象。为什么我不能将它们与的实例进行比较?整数[]与整数不同。它们是两个完全不同的类:通过检查Integer[].class==Integer.class,可以看到这一点,这将产生false 这并不奇怪:一个是数组类型,另一个不是。

为什么这段代码会抛出编译错误

Integer[] arr  = new Integer[3];
if (arr instanceof Integer) {
    System.out.println("true");
}

arr是一个对象,同时Integer是一个对象。为什么我不能将它们与
实例进行比较?

整数[]
整数
不同。它们是两个完全不同的类:通过检查
Integer[].class==Integer.class
,可以看到这一点,这将产生
false

这并不奇怪:一个是数组类型,另一个不是。您可以对
整数调用
Integer.intValue()
,对
整数[]
调用
Integer.length
,但不能调用
Integer.length
Integer[].intValue()


此外,这两个类唯一常见的超类型是
对象
,因此
整数
引用无法存储
整数[]
,反之亦然。

整数[]
整数
不同。它们是两个完全不同的类:通过检查
Integer[].class==Integer.class
,可以看到这一点,这将产生
false

这并不奇怪:一个是数组类型,另一个不是。您可以对
整数调用
Integer.intValue()
,对
整数[]
调用
Integer.length
,但不能调用
Integer.length
Integer[].intValue()

此外,这两个类唯一常见的超类型是
Object
,因此
Integer
引用无法存储
Integer[]
,反之亦然

JLS 15.20.2。类型比较运算符
instanceof

如果引用类型的关系表达式的强制转换(§15.16)将作为编译时错误被拒绝,那么
关系表达式的
实例同样会产生编译时错误。

其中
instanceof
的使用是

if (RelationalExpression instanceof ReferenceType)
由于
Integer
Integer[]
之间的强制转换失败,因为两者都不是另一个的子类型(它们的常见超类型是
Object
),
instanceof
给出了一个复杂的错误

不兼容的条件操作数类型Integer[]和Integer

JLS 15.20.2。类型比较运算符
instanceof

如果引用类型的关系表达式的强制转换(§15.16)将作为编译时错误被拒绝,那么
关系表达式的
实例同样会产生编译时错误。

其中
instanceof
的使用是

if (RelationalExpression instanceof ReferenceType)
由于
Integer
Integer[]
之间的强制转换失败,因为两者都不是另一个的子类型(它们的常见超类型是
Object
),
instanceof
给出了一个复杂的错误

不兼容的条件操作数类型Integer[]和Integer


非常感谢你的回答。我知道,整数[]和整数不一样。但我误解了“instanceof”的工作原理。现在我明白了!!!非常感谢你的回答。我知道,整数[]和整数不一样。但我误解了“instanceof”的工作原理。现在我明白了!!!谢谢!正是我想知道的!谢谢!正是我想知道的!