It holds true for (Integer) 1 == (Integer) 1
, which seems legitimate.
So why it's having excursion for (Integer) 222
's equality?
It holds true for (Integer) 1 == (Integer) 1
, which seems legitimate.
So why it's having excursion for (Integer) 222
's equality?
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);
}