一个Integer赋值的问题

本文探讨了Java中的Integer对象与常量池的关系。当Integer值在-128到127之间时,它们会复用常量池中的对象,导致比较返回true,例如a==b、a==c和c==d。而对于大于127的Integer实例,如e和f,每次都会创建新对象,比较返回false。这揭示了Java内存管理和对象引用的细节。
摘要由CSDN通过智能技术生成

先看一个代码段:

public class csdn_Integer {
    public static void main(String[] args) {
        int a = 11;
        int b = 11;
        Integer c = 11;
        Integer d = 11;
        Integer e = new Integer(11);
        Integer f = 555;
        Integer g = 555;
        System.out.printf("a==b:%b\na==c:%b\nc==d:%b\nc==e:%b\ne==f:%b\n",a==b,a==c,c==d,c==e,f==g);
    }
}

结果 :

a==b:true
a==c:true
c==d:true
c==e:false
e==f:false

Process finished with exit code 0

分析:

1.与String类似,Integer也有常量池,通过Integer = x;定义的变量会先在常量池查找(且Integer和int共享常量池),如果存在就引用,没有就在常量池新建;new Integer(x);则不查找常量池,直接在堆中新建。

注意:这里Integer使用常量池的数据范围是-128 ~~ 127。超过这个范围的数据不引用常量,全部新建。

 

/**
 * 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
 * jdk.internal.misc.VM class.
 */

2.对于f与g,因为555 > 127所以无论怎么声明都是新建。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值