在Java 7中比较Object和int [英] Comparing Object and int in Java 7

查看:603
本文介绍了在Java 7中比较Object和int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名高级解决方案架构师,但我最近偶然发现了一个让我停下来思考的问题...



对我来说,一个错误,但是当我的一个同事问我为什么Eclipse没有显示一个,我不能回答任何东西。

  class A {
public static void main(String ... args){
System.out.println(new Object()== 0);
}
}



我调查发现,它确实引发了一个错误:

 无法比较的类型:Object和int 

但现在在1.7它编译正确。



请问,什么新功能保证这种行为? p>

解决方案

什么新功能保证这种行为是什么意思? ? 1.7正在修复1.6中的问题。 new Object()== 0 应该有从不产生错误,总是导致自动装箱触发。 p>

没有理由为什么

  Object a = 5; 

是正确的,而不是表达式

  a == 3 

或甚至

  a == 5 

这是非常奇怪,恕我直言,与语言规范本身矛盾。



从动态的角度来看, a == 5 仍然评估为 false while (Integer)a == 5 或甚至(int)a == 5 计算 true 。原因是autounboxing被设计为从不产生 ClassCastException s,因此只对静态的包装类型。后两种情况是显式转换,因此通常允许 ClassCastException


I am a senior Solutions Architect, but I recently stumbled on a question that made me stop and think...

To me, the code below should always trigger an error, but when one of my colleagues asked me why Eclipse didn't show one, I couldn't answer anything.

class A {
    public static void main(String... args) {
        System.out.println(new Object() == 0);
    }
}

I've investigated and found that with source level 1.6 it indeed throws an error:

incomparable types: Object and int

But now in 1.7 it compiles ok.

Please, what new feature does warrant this behavior?

解决方案

What do you mean by "what new feature does warrant this behavior?" ? 1.7 is fixing an issue present in 1.6. new Object() == 0 should have never produced an error, and always caused autoboxing to trigger.

There was simply no reason why

Object a= 5 ;

was correct, and not the expression

a == 3

or even

a == 5

It was extremely weird and, IMHO, contradictory with the language specification itself.

From a dynamic point of view, though, a == 5 still evaluates to false while (Integer)a == 5 or even (int)a == 5 evaluate to true. Reason is that autounboxing was designed to never produce ClassCastExceptions and thus occur for wrapper types only, statically. The later two cases are explicit casts so ClassCastExceptions are generally allowed.

这篇关于在Java 7中比较Object和int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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