Thursday, July 13, 2017

In Java, two Integer objects with the same value are not == to each other, most of the time

Today I've discovered, to my dismay, that two Integer objects with the same value compared with the == operator may return false, because they are different objects. So you need to use .equals (before you check for null, of course). I was about to write a scathing blog entry on how much Java sucks, but then I discovered this amazing link: Java gotchas: Immutable Objects / Wrapper Class Caching that explains that the Integer class creates a cache of 256 values so that everything between -128 and 127 is actual equal as an instance as well.

Yes, folks, you've heard that right. I didn't believe it, either, so I wrote a little demo code:
Integer i1 = Integer.valueOf(1);
Integer i2 = Integer.valueOf(1);
boolean b1 = i1 == i2; // true

i1 = Integer.valueOf(1000);
i2 = Integer.valueOf(1000);
boolean b2 = i1 == i2; // false

i1=1;
i2=1;
boolean b3 = i1 == i2; // true

i1=1000;
i2=1000;
boolean b4 = i1 == i2; // false

i1=126;
i2=126;
boolean b5 = i1 == i2; // true

i1++;
i2++;
boolean b6 = i1 == i2; // true

i1++;
i2++;
boolean b7 = i1 == i2; // false

i1 = 2000;
i2 = i1;
boolean b8 = i1 == i2; // true

i1++;
i1--;
boolean b9 = i1 == i2; // false


Update: the same thing also applies to Strings. Two strings with the same value are not == although they are immutable, so even the same string won't be equal to itself after changes. Fun!

I now submit to you that "sucks" applies to many things, but not to Java. A new term needs to be defined for it, so that it captures the horror above in a single word.

0 comments: