为什么integer比较一定要用equels

public static void main(String[] args) {
        Integer a = null;
        System.out.println(1 == a);
        System.out.println(a == 1);
    }

这段代码第一次打印就会报错,是因为integer类型会自动拆箱。
正确方法应该是

 public static void main(String[] args) {
        Integer a = null;
        System.out.println(Integer.valueOf(1).equals(a));
    }

在integer的值在-128~127之间的时候是可以使用==号来比较。但是当值大于127或者为null的时候是非常容易出问题的。所以为了避免这种低级错,所有的integer比较都要用equals,尽管你可能明确知道他是不会出错的。

 public static void main(String[] args) {
        Integer a = new Integer(128);
        Integer b = new Integer(128);
        Integer c = new Integer(127);
        Integer d = new Integer(127);
        System.out.println(b==a);//false
        System.out.println(d==c);//false
    }
public static void main(String[] args) {
        Integer a = 128;
        Integer b = 128;
        Integer c = 127;
        Integer d = 127;
        System.out.println(b==a);//false
        System.out.println(d==c);//true
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值