码迷,mamicode.com
首页 > 其他好文 > 详细

关于Integer 和Double包装类创建对象时的底层解析

时间:2020-01-10 22:28:39      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:关于   code   class   没有   类型   ble   数组   int   调用   

public void method1() {
    Integer i = new Integer(1);
    Integer j = new Integer(1);
    System.out.println(i == j);
    Integer m = 1;
    Integer n = 1;
    System.out.println(m == n);//True
    Integer x = 128;
    Integer y = 128;
    System.out.println(x == y);//False
}

如题,当数值大于等于128时,创建的俩个对象地址就不一样了,这个原因还得看Integer的源码

1 public static Integer valueOf(int i) {
2     if (i >= IntegerCache.low && i <= IntegerCache.high)//-128~127
3         return IntegerCache.cache[i + (-IntegerCache.low)];
4     return new Integer(i);
5 }

这个IntegerCache 数组是包装类自己创建的缓存数组,里面存放着【-128,127】的整数,当数值在这个范围时,会从这个数组中直接取值,当数值不在这个范围时,就会新建对象,所以地址就会不一样

-------------------------------------------------

那么Double类型的呢

    public static void main(String[] args) {
        double a = 2.0;
        double b = 2.0;
        Double c = 2.0;
        Double d = 2.0;
        System.out.println(a == b);//true
        System.out.println(c == d);//false
        System.out.println(a == d);//true
    }

进源码

public static Double valueOf (double d){
               return  new  Double (d)   ;
    
}    

显然,Double没有Integer花里胡哨,只有调用就新建一个对象

关于Integer 和Double包装类创建对象时的底层解析

标签:关于   code   class   没有   类型   ble   数组   int   调用   

原文地址:https://www.cnblogs.com/yangxusun9/p/12178093.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!