我们在使用到Integer的时候,有如下一段代码
Integer i = 1
Integer j = 1
System.out.pringln(i == j)
结果会返回True,是不是非常奇怪,按照对象,i和j应该各代表一个对象地址,两个地址相比较应该不同才对。
谜团揭底
Integer i = 1,用到了基本类型的装箱机制, i = Integer.valueof(1),查看一下源代码
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
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) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
IntegerCache就是享元模式,享元模式是把数据创建好缓存起来,减少内存的占用。默认情况下,从1-127的数字都被静态缓存起来,所以代码中i和j返回都是一个静态对象,所以其地址相同。
小结
享元模式和单例模式都与内存有关,但是使用的意图不一样,单列模式是为了保持内存的全局唯一,享元模式是为了减少内存占用。
网友评论