關於Integer 和Double包裝類建立對象時的底層解析

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】的整數,當數值在這個範圍時,會從這個數組中直接取值,當數值不在這個範圍時,就會新建對象,因此地址就會不同緩存

-------------------------------------------------spa

那麼Double類型的呢code

    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花裏胡哨,只有調用就新建一個對象blog

相關文章
相關標籤/搜索