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值时也可以判断)

相关推荐
努力努力再努力wz几秒前
【Linux进阶系列】:线程(上)
java·linux·运维·服务器·数据结构·c++·redis
极客柒4 分钟前
Unity 协程GC优化记录
java·unity·游戏引擎
我要去腾讯5 分钟前
Springcloud核心组件之Sentinel详解
java·spring cloud·sentinel
czhc11400756636 分钟前
Java117 最长公共前缀
java·数据结构·算法
weixin_3077791338 分钟前
AWS Elastic Beanstalk 实现 Java 应用高可用部署指南
java·开发语言·云计算·aws·web app
萝卜白菜。1 小时前
关于Java EE应用中xml解析类的问题
xml·java·java-ee
一米阳光zw1 小时前
Spring Boot中使用 MDC实现请求TraceId全链路透传
java·spring boot·后端·traceid·mdc
王元_SmallA1 小时前
pgsql:connection failed connection to server at
java·后端
高山上有一只小老虎1 小时前
购物消费打折
java·算法
tuokuac1 小时前
@Configuration类中定义的@Bean方法
java