2

It holds true for (Integer) 1 == (Integer) 1, which seems legitimate.

So why it's having excursion for (Integer) 222's equality?

Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75
Snehal Masne
  • 3,403
  • 3
  • 31
  • 51

1 Answers1

9

Integer is a class. So to compare objects you need to use equals instead of ==

What actually happens with shorter Integer is that if you get an Integer using the method valueOf you get always the same cached instance for values between -128 and 127. So in this case == works.

It doesn't work if you instead of using valueOf create a new instance explicitly with the operator new.


For To be more clear I write the current implementation of valueOf

public static Integer valueOf(int i) {
    final int offset = 128;
    if (i >= -128 && i <= 127) { // must cache
        return IntegerCache.cache[i + offset];
    }
    return new Integer(i);
}
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56