It's because you're comparing Integer
instances (which are objects) with ==
. When you compare objects with ==
, you're checking that they're the same object, not that they're equivalent.
So why does it work with values less than 128? Because the JVM caches and reuses Integer
instances for those values. You're using autoboxing by assigning primitives to Integer
variables, and boxing uses Integer.valueOf
. From the JavaDoc:
This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
But for other values, it (probably) creates new instances as you go.
For what you're doing, use int
primitives instead of Integer
instances. If you ever need to use Integer
instances, compare them with equals
instead of ==
.
if (i.equals(j))