Dec 18

The Evils of Equals and Autoboxing

Category: Java, Programming

This was a fun, if particularly stupid, one:

public void method check(int value){
  if(this.x == value)
    //do whatever

the previous works as long as x and value are small, but not when they are big. Why? Because x is an Integer not an int. Java helpfully autoboxes the int by building an Integer and then does a pointer comparison. This still works for small numbers because java caches the lower Integer constants rather than creating them on the fly all the time so new Integer(value) actually resolves to the same object as x, but once the number gets big enough Java has to create a new object and then suddenly the comparison fails.

I actually don’t blame autoboxing for this one. Autoboxing was a good idea. Having == mean pointer equality (or really fundamental type equality) rather than actual equality combined with not modeling all fundamental types as objects was not such a hot move.


Comments are closed.