先看代码实例现象:

问题:为什么都是比较数值,第一个为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

最新文章

  1. linux 下mysql的安装,并设置必要的密码
  2. Dir /U /c 输出Unicode字符的特性
  3. namespace使用总结
  4. 11gR2 Clusterware and Grid Home - What You Need to Know
  5. const int *p与int *const p的区别(转:csdn,suer0101)
  6. 初学Ajax(三)
  7. ie6背景透明的设置方法 ie6背景颜色透明和png图像透明解决方法
  8. C++学习笔记32 断言函数
  9. SQL中判断字符串中包含字符的方法
  10. 微信小程序之bindtap事件绑定传参
  11. CSS3学习笔记--media query 响应式布局
  12. Keras官方中文文档:函数式模型API
  13. css与html基础收集
  14. mysql查看存储过程函数
  15. MySQL 三 通过yum源安装指定版本的mariadb
  16. linux上jenkins连接windows并执行exe文件
  17. 中断 http请求 正在加载 取消http请求
  18. Shell变量while循环内改变无法传递到循环外
  19. List 集合的交集
  20. [转]jQuery选择器 (详解)

热门文章

  1. SpreadJS电子表格
  2. VC++ 简单的打印功能(对话框模式下)
  3. oracle 数据库学习3 --oracle 数据库中常使用的函数
  4. 基于jquery封装的颜色下拉选择框
  5. 解决 Gnome3 窗口背景是黑色的问题
  6. arduino编程语言Wiring参考手册API
  7. CentOS6.5 vsftpd 配置
  8. 使用HttpClient 发送get、post请求,及其解析xml返回数据
  9. Android WIFI 分析(一)
  10. Android 7.0 UICC 分析(一)