Comparing Object and int in Java 7

会有一股神秘感。 提交于 2019-12-12 10:33:29

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18500209/comparing-object-and-int-in-java-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!