允许“布尔”和“对象”的平等比较? [英] Equality comparison of `boolean` and `Object` allowed?

查看:148
本文介绍了允许“布尔”和“对象”的平等比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码

public class TestComparison {
    public static void main(String[] args) throws Exception {
        boolean b = true;
        Object o = new Boolean(true);
        System.out.println("comparison result: "+ 
            (o == b)); // Eclipse complains about this expression
    }
}

编译没有错误 javac V1.7.0_15,并在运行时打印false。但是,Eclipse Juno抱怨不兼容的操作数类型Object和boolean。

compiles without errors with javac V1.7.0_15, and prints "false" when run. However, Eclipse Juno complains about "Incompatible operand types Object and boolean".

显然javac autoboxes的原始布尔值 b ,然后通过对象相等性比较 o 和autoboxed b ,生成 false ,而Eclipse拒绝自动装箱。

Apparently javac autoboxes the primitive boolean b, and then compares o and autoboxed b by object equality, yielding false, while Eclipse refuses to do the autoboxing.

根据Java语言规范,哪个是正确的行为?我应该在哪里提出错误?

Which is the right behaviour according to the Java Language Specification? Where should I file a bug?

注意:如果我更改了 o 到 Boolean ,事情按预期工作:Eclipse接受代码,代码打印true。

Note: If I change the type of o to Boolean, things work as expected: Eclipse accepts the code, and the code prints "true".

ideone.com上的Runnable版本

推荐答案

这是您的项目语言级别设置。您可能正在使用具有Java 6语义的Java 7编译器。我在这里没有Eclipse,但是我在IntelliJ中复制了它,当语言级别在Java 6上时,即使我使用的编译器是7.我猜Eclipse也是如此。 此链接解释。

It's your project language level setting. You are probably using a Java 7 compiler with Java 6 semantics. I don't have Eclipse here, but I reproduced it in IntelliJ, which gave errors when the language level was on Java 6, even though the compiler I used was 7. I guess Eclipse has the same. This link explains it.

这篇关于允许“布尔”和“对象”的平等比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆