为什么Integer num03 = 250; Integer num04 = 250;两个数相比较返回值是false?

上代码(●’◡’●):

public class Demo {
    public static void main(String[] args) {
        Integer num01 = 50 ;
        Integer num02 = 50 ;
        Integer num03 = 250;
        Integer num04 = 250;
        Double num05 = 1.0;
        Double num06 = 1.0;
        System.out.println(num01 == num02); //true
        System.out.println(num03 == num04); //false
        System.out.println(num05 == num06); //false
    }
}

输出结果:

true
false
false

Process finished with exit code 0

如何将一个基本数据类型转换成为一个Integer对象:
调用Integer.valueOf()方法 点进valueOf源码查看:

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i); //如果不在上述的范围,会创建一个新的对象
    }
   private static class IntegerCache {
        static final int low = -128; //最小值-128
        static final int high;       //最大值
        static final Integer cache[];//数组

50这个数是在上述的范围里(> -128 && <127)
所以num01 和 num02 返回的值都是cache数组里面的指定对象,所以相等。
而 num03 和 num04 不在上述范围里,会创建有一个新的对象,所对应的地址也会不同,所以返回false!

点进Double.valueOf 的源码

public static Double valueOf(double d) {
        return new Double(d); //每次都会创建新的对象
    }

每次都会创建新的对象,地址值不同,返回false。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值