Integer、Long 等包装类 == 值判断、地址判断与缓存

先看下以下代码和输出

java 复制代码
   public static void main(String[] args) throws Exception{
        Integer a=-128;
        Integer aa=-128;
        System.out.printf("a=aa? %s \n",a==aa);
        Integer b=127;
        Integer bb=127;
        System.out.printf("b=bb? %s \n",b==bb);
        Integer c=128;
        Integer cc=128;
        System.out.printf("c=cc? %s \n",c==cc);
        Integer d=126;
        Integer dd= new Integer(126);
        System.out.printf("d=dd? %s \n",d==dd);
        int e=12611;
        Integer ee= new Integer(12611);
        System.out.printf("e=ee? %s \n",e==ee);
        int f=12611;
        Integer ff= 12611;
        System.out.printf("f=ff? %s \n",f==ff);

    }

a=aa? true
b=bb? true
c=cc? false
d=dd? false
e=ee? true
f=ff? true

那么为什么会会出现这样的结果呢?

这是因为==只有在Java基本类型(short,int,long,byte,char,float,double,boolean)中比较的是值,其他类型中比较的是内存地址。因此,InteGer类中==比较的是内存地址,而不是值从而导致c和cc因为内存地址不相同导致c==cc不相同。

那为什么a=aa 和 b=bb 运行起来又是ture呢?

这是因为Integer类在-128至127(默认)区间的Integer实例缓存到cache数组中,所以

a=aa 和 b=bb都是true

那为什么d=dd 运行起来又是ture呢,他们都在-128和127之间啊?

这是因为区间的Integer实例缓存不包含new出来的对象

总结

Integer 和 int == 这样判断相等是可以的,

而Integer 和 Integer 要判断相等,推荐用equals (NULL值时也可以判断)

相关推荐
十八旬2 分钟前
苍穹外卖项目实战(day7-1)-缓存菜品和缓存套餐功能-记录实战教程、问题的解决方法以及完整代码
java·数据库·spring boot·redis·缓存·spring cache
Java微观世界13 分钟前
匿名内部类和 Lambda 表达式为何要求外部变量是 final 或等效 final?原理与解决方案
java·后端
SimonKing31 分钟前
全面解决中文乱码问题:从诊断到根治
java·后端·程序员
你三大爷1 小时前
再探volatile原理
java
2301_781668611 小时前
Redis 面试
java·redis·面试
郑洁文1 小时前
基于SpringBoot的天气预报系统的设计与实现
java·spring boot·后端·毕设
沃夫上校1 小时前
MySQL 中文拼音排序问题
java·mysql
Dcs1 小时前
用 Python UTCP 直调 HTTP、CLI、MCP……
java
快乐肚皮2 小时前
fencing token机制
java·fencing token
叶落阁主2 小时前
Neovim 插件 i18n.nvim 介绍
java·vue.js·vim