12
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 that ==
is different from equals()
12
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 that ==
is different from equals()
11
Because the class Integer
cache 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 some snippets of the class source code Integer
, 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));
}
3
This is because the Integer Class uses the Flyweight design pattern.
The Integer class creates an immutable Singleton object for each of the numbers from -128 to 127 so that these objects can be shared throughout the application generating memory savings.
Browser other questions tagged java whole
You are not signed in. Login or sign up in order to post.
The explanation is correct. However, do not stick to this source code of the Integer class because it is not the Oracle code that is in the standard JVM. It is openjdk code, which may or may not be the same as the original implementation.
– pablosaraiva
@pablosaraiva Thanks for the tip. I have updated the text to clarify this point.
– Victor Stafusa
Remembering that there is how to manipulate the size of this cache.
– everton