IntegerCache类
2024-08-28 06:20:29
先看代码实例现象:
问题:为什么都是比较数值,第一个为true,第二个确为false呢?
查找源码(java.lang.Integer),看到如下代码:
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/ 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() {}
}
原来是因为Integer类型使用了缓存机制,即默认在JVM启动的时候设定了[-127~128]范围内的int包装类,这样在实际使用并在范围内的时候,直接从缓存中取实例,不用再new了。
这样做的好处是:提升JVM的性能。
坏处是:用==来比较Integer类型的时候,可能出现问题。
解决方案:
- 设定JVM启动参数-XX:AutoBoxCacheMax=<size>,改编默认的缓存最大(不推荐)
- 不要用==比较大小,用equals比较(推荐)
同样使用缓存的还有ShortCache, LongCache
最新文章
- linux 下mysql的安装,并设置必要的密码
- Dir /U /c 输出Unicode字符的特性
- namespace使用总结
- 11gR2 Clusterware and Grid Home - What You Need to Know
- const int *p与int *const p的区别(转:csdn,suer0101)
- 初学Ajax(三)
- ie6背景透明的设置方法 ie6背景颜色透明和png图像透明解决方法
- C++学习笔记32 断言函数
- SQL中判断字符串中包含字符的方法
- 微信小程序之bindtap事件绑定传参
- CSS3学习笔记--media query 响应式布局
- Keras官方中文文档:函数式模型API
- css与html基础收集
- mysql查看存储过程函数
- MySQL 三 通过yum源安装指定版本的mariadb
- linux上jenkins连接windows并执行exe文件
- 中断 http请求 正在加载 取消http请求
- Shell变量while循环内改变无法传递到循环外
- List 集合的交集
- [转]jQuery选择器 (详解)