Java primitive type comparison – A wat look

Not long ago, we had a not too nice issue related to mismatch between int and long variables. As the concrete variables were coming from 1) a model created by others and 2) another model created by us, the solution did not appear to be simple.

We were thinking, if we could compare the variables by value consistently without the concrete type equality, we would not need to support both int and long numbers in our model, so we asked our collegue, Gábor Bergmann to experiment a bit with the comparison.

Sadly, the result is that there is no reasonable way to compare longs and integers by value. However, we found a truly nice wat moment, almost fitting to the issues presented by Gary Bernhardt in a talk called WAT at CodeMash 2012 (or instead of the video, you could have a look at http://www.shopify.com/technology/5370262-wat-a-funny-look-at-ruby-and-javascript-oddities).

Because of Java is statically typed, most inconsistencies of Javascript do not apply here. However, the implicit contracts of Java are sometimes broken, just as the following code snippet shows (it is Gábor’s work entirely, I only changed only the white spaces):

Basically, when comparing primitive types and their boxed values, if you have two different types, all hell’s might break loose. Sometimes two values are considered equal when using ‘==’ but not when using Object.equals. Even worse, transitivity can also be broken.

I cannot think about any possible reason for this behavior, but we could reproduce it issue consistently across different computers using Java 1.6, so this appears to be according to be designed that way.

If someone could provide some reasonable explanation, I would be glad for it. Then we could learn something nice instead of just laughing a bit. Otherwise, be careful with primitive comparison…