Integer对象缓存机制

不止是Integer,Long,Float等都存在对象缓存机制,比如Integer的缓存值在于-128——127,如果使用自动装箱,则在这个范围内的对象引用是相等;
但如果是new出来的,因为是新开创空间,即使是在这个范围内,也是不相等的;

测试如下:

 Integer a = 500;
        Integer b = 500;
        Integer c = 127;
        Integer d = 127;
        Integer e = new Integer(127);
        Integer f =new Integer(127);

        System.out.println(a == b);//false
        System.out.println(a.equals(b));//true
        System.out.println((c==d));//true
        System.out.println(c.equals(d));//true
        System.out.println(e==d);//false
        System.out.println(e.equals(d));//true
        System.out.println(e==f);//false
        System.out.println(e.equals(f));//true

只要值相等,equals都是相等的,因为在基本类型的包装类中都对于equals进行重写,如Integer对于equals进行重写,先将对象通过intValue()转成基本数据类型,然后再用"=="进行比较的;

  • 而其它没有重写equals()方法的类,比如我们自己定义的类,在使用equals()方法时,都是调用Object类的equals(),最终用"=="比较地址;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值