简体   繁体   中英

Comparing Object and int in Java 7

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 ClassCastException s and thus occur for wrapper types only, statically. The later two cases are explicit casts so ClassCastException s are generally allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM