Java之128陷阱

128陷阱

先看如下代码,发现同是==判断 a=10时与A=1000时竟然出现两种结果:

 public static void main(String[] args) {
        Integer a=10;
        Integer b=10;
        Integer c=new Integer(10);
        System.out.println(a==b);//true
        System.out.println(a==c);//false
        System.out.println(a.equals(b));//true
        System.out.println(a.equals(c));//true
        System.out.println("———————————————");
        Integer A=1000;
        Integer B=1000;
        Integer C=new Integer(1000);
        System.out.println(A==B);//false//注意这个竟然是false!!
        System.out.println(A==C);//false
        System.out.println(A.equals(B));//true
        System.out.println(A.equals(C));//true
    }

因为 有时需要将基本类型转换成对象,所以每个基本类型都又对应的类——这样的类被称为包装器。
例如:Integer类对应基本类型int
1.对象包装器是不可变的,一旦构造,不允许更改其中的值。
2.对象包装器是final,不允许定义其子类。
所以在用Integer时会涉及到自动拆箱装箱

自动装箱规范要求-128~127之间的short和int被包装到固定对象中
超出这个范围,哪怕自动装箱也不是同一个

所以这个说明A、B的装箱是两个,所以指向不同、所以==为false

        Integer A=1000;
        Integer B=1000;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值