java中的instanceof运算符用于比较不同的类 [英] instanceof operator in java for comparing different classes
问题描述
我试图了解Java中的instanceof运算符是如何工作的并且面临一个非常奇怪的问题。
I was trying to see how instanceof operator in Java works and am facing a very odd issue.
public static void main(String[] args) {
Map m = new HashMap();
System.out.println("m instanceof Date: " + (m instanceof Date));
}
上述内容按预期返回false。但是,
The above returns false as expected. However,
public static void main(String[] args) {
HashMap m = new HashMap();
System.out.println("m instanceof Date: " + (m instanceof Date));
}
这甚至都没有编译。我收到错误
This does not even compile. I get an error
inconvertible types
found : java.util.HashMap
required : java.util.Date
我在这里缺少什么?
我正在使用IntelliJ Idea 11.
What am I missing here? I am using IntelliJ Idea 11.
推荐答案
来自Java语言规范3.0,第15.20.2节:
From the Java Language Specification 3.0, section 15.20.2:
如果对于ReferenceType的RelationalExpression的强制转换将被
作为编译时错误拒绝,则关系实例为
表达式同样会产生编译时错误。在这样的
情况下,instanceof表达式的结果永远不会是
true。
If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.
因为你可以不能将 HashMap
中的演员表编译成日期
,你无法编译 instanceof
在两者之间进行测试。
Since you can't compile a cast from a HashMap
to a Date
, you can't compile an instanceof
test between the two either.
这篇关于java中的instanceof运算符用于比较不同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!