Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparison between wrapper objects - weird behavior

 
Larry Olson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(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?
 
Henry Wong
author
Marshal
Pie
Posts: 21219
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Larry Olson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Henry Wong
author
Marshal
Pie
Posts: 21219
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic