Comparison between wrapper objects - weird behavior
Larry Olson
Ranch Hand
Joined: Feb 03, 2009
Posts: 142
posted
0
(A) System.out.println(new Long(10) > new Integer(10));
(B) System.out.println(new Long(10) == new Integer(10));
(A) compiles and runs fine, whereas (B) fails to compile with the following error:
incomparable types: java.lang.Long and java.ang.Integer
When using "==", the compiler complains that the types aren't comparable, whereas it doesn't when using ">". How come? Why "==" can't compare when ">" can? I am at a total loss to understand this. Why would the java designers do this?
Of course I do know that == results in two references being compared to each other (and not the object state). Even in that case, shouldn't a == between two different wrapper object types be accepted by the compiler and result in a false, instead of resulting in a compiler error?
This message was edited 1 time. Last update was at by Larry Olson
In the first case, it is obvious that the objects should be unboxed, as there is no way to compare if one object is greater than another object via the ">" operator. In the second case, it is not obvious that unboxing should be applied. So, it isn't, as autoboxing doesn't have priority over reference comparison.
Henry
This message was edited 1 time. Last update was at by Henry Wong
Why isn't the compiler smart enough to figure out that the two objects being compared are wrapper objects for primitives and then unbox them and do the comparison? Why not? What will go wrong if we do that?
Compiler are written to specifications. And specifications are written to be very very specific -- sort of like legalese. There are no room for implementation details like do the "smart enough" thing.
Reference comparison is done when two objects are compared with the "==" operator, as per specification. Of course, you can always send a request to Sun Oracle to have the specification changed.
Henry
This message was edited 2 times. Last update was at by Henry Wong
subject: Comparison between wrapper objects - weird behavior