比较Integer的时候,不要用==。

查看Integer的源码,如下:

    /**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

通过注释可以知道,为了更好的空间和时间性能,Integer会缓存频繁使用的数值,数值范围为-128到127,在此范围内直接返回缓存值。

IntegerCache.low 是-128,IntegerCache.high是127,如果在这个区间内,他就会把变量i当做一个变量,放到内存中;

但如果不在这个范围内,就会去new一个Integer对象,

而如果两个Integer值都不在这个范围内,那么就会new了两个对象实例,两个对象用==比较肯定是false。

解决方法

比较Integer的值有两种方法,

1.一个是用equals()比较,但是注意要判空,避免空指针异常。

2.一个是用intValue()转成int比较。

示例如下:

        Integer value1=129;
Integer value2=129;
if(value1.intValue()==value2.intValue()){
// ...
}

参考资料:

https://blog.csdn.net/luohao_/article/details/86607686

最新文章

  1. test [ ] 四类
  2. TP框架,根据当前应用状态对应的配置文件
  3. tinyfox for linux 独立版 fox.sh
  4. Linux命令之md5sum
  5. linux下ssh/scp无密钥登陆方法
  6. Go语言学习笔记一(语法篇)
  7. Filter过滤非法字符
  8. cocos2d-x 动画加速与减速
  9. Android学习6&mdash;单元测试的使用
  10. DES加密解密帮助类
  11. 【FlashPlayer】-Debug版本-开发人员推荐
  12. 四.js 正则表达式
  13. linux下把动态链接库加入环境变量的几种方式
  14. 洛谷P3953 逛公园
  15. JavaScript正则表达式在不同浏览器中可能遇到的问题
  16. [Winform]缓存处理
  17. Day7 访问权限
  18. 洛谷 P4593 [TJOI2018]教科书般的亵渎
  19. QQ互联
  20. mariadb 10.1.10安装

热门文章

  1. dubbo循序渐进 - nacos安装
  2. 编写可维护的JavaScript-随笔(六)
  3. Unable to establish SSL connection
  4. 关于logging模块
  5. OSX 优化配置
  6. 关于子类和父类中的this的用法
  7. MongoDB安装启动教程
  8. Ueditor 自动设置上传图片的宽度或高度
  9. linux中/dev/null与2&gt;&amp;1讲解
  10. 修改linux环境变量导致系统命令不可用,-bash: xx: command not found