Why
System.out.println(Integer.valueOf("0")==Integer.valueOf("0"));
System.out.println(Integer.valueOf("1000")==Integer.valueOf("1000"));
returns
true
false
?
ps. I know ==
is different from equals()
Why
System.out.println(Integer.valueOf("0")==Integer.valueOf("0"));
System.out.println(Integer.valueOf("1000")==Integer.valueOf("1000"));
returns
true
false
?
ps. I know ==
is different from equals()
Because the Integer
class caches values between -128 and 127.
Look at this:
System.out.println(Integer.valueOf("-129") == Integer.valueOf("-129")); // Dá false.
System.out.println(Integer.valueOf("-128") == Integer.valueOf("-128")); // Dá true.
System.out.println(Integer.valueOf("127") == Integer.valueOf("127")); // Dá true.
System.out.println(Integer.valueOf("128") == Integer.valueOf("128")); // Dá false.
Here is some snippets of the Integer
source code, as implemented in OpenJDK :
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low));
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
This is because the Integer Class uses the FlyWeight design pattern.
The Integer class creates an unchanging Singleton object for each of the numbers from -128 to 127 so that these objects can be shared throughout the application, generating memory savings.