You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
publicstaticIntegervalueOf(inti) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
returnIntegerCache.cache[i + (-IntegerCache.low)];
returnnewInteger(i);
}
privatestaticclassIntegerCache {
staticfinalintlow = -128;
staticfinalinthigh;
staticfinalIntegercache[];
static {
// high value may be configured by propertyinth = 127;
StringintegerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
inti = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUEh = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatExceptionnfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = newInteger[(high - low) + 1];
intj = low;
for(intk = 0; k < cache.length; k++)
cache[k] = newInteger(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)assertIntegerCache.high >= 127;
}
privateIntegerCache() {}
}
首先看一段代码
输出结果会是多少呢,相信每个人心中都会有自己的答案,倒不如直接运行一下看看:
现在就有了疑问,为什么两个输出的结果不一样呢,这里就设计到了Integer设计了,我们可以用
javap
命令反编译一下字节码,看看到底发生了什么:从字节码中可以看出是调用了Integer类的静态方法valueOf(),因此我们再进去Integer的源码研究一下:
那么这里的IntegerCache类有什么秘密呢,我们也进去看一下源码,IntegerCache是Integer的一个私有内部类,构造器也是
私有的,保证了安全性,通过源码可以看出,low的值默认为-128,修饰符为
static final
,因此不可再更改其值,而high的值可以通过设置参数
-XX:AutoBoxCacheMax
来设置,同时内部维护了一个static final
的Integer
数组.可以看出如果大于IntegerCache.low并且小于IntegerCache.high的话,则直接返回缓存中的对象,
因此用
==
比较肯定是相等的,如果if
的条件不成立的话,那么就会new
一个新的Integer对象返回,因此肯定是不相等的
对于Boolean则是内部维护了两个常量:
对于Short和Long其实和Integer的实现差不多,只不过缓存的范围写死在了代码里面:
对于Double和Float来说,则是直接返回,不进行任何缓存的操作:
The text was updated successfully, but these errors were encountered: