是否允许对“boolean"和“Object"进行相等比较? [英] Equality comparison of `boolean` and `Object` allowed?

查看:22
本文介绍了是否允许对“boolean"和“Object"进行相等比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码

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自动装箱原始布尔值b,然后通过对象相等比较o和自动装箱的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 接受代码,并且代码打印真实".

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 上的可运​​行版本

推荐答案

这是您的项目语言级别设置.您可能正在使用具有 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.

这篇关于是否允许对“boolean"和“Object"进行相等比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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