先來看一段代碼:
public class Main{ public static void main(String[] args){ Integer num1 = 100; Integer num2 = 100; Integer num3 = 200; Integer num4 = 200; '''//輸出結果''' System.out.println(num1==num2); System.out.println(num3==num4); }}猜猜結果是什么?
很多人都會認為結果全為true,但結果去不是這樣的
true
false
為什么是這樣的結果?如果用內存來解釋結果的話,num1和num2指向的是同一個對象,而num3和num4則指向的確是不同的對象。接下來就告訴你為什么,看一看Integer類型的valueof方法的源碼:
public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; return new Integer(i); }其中IntegerCache的實現:
'''// IntegerCache,一個內部類,注意它的屬性都是定義為static final''' private static class IntegerCache { static final int high; '''//緩存上界,暫為null''' static final Integer cache[]; '''//緩存的整型數組''' '''// 塊,為什么定義為塊''' static { final int low = -128; '''// 緩存下界,不可變了。只有上界可以改變''' '''// high value may be configured by property''' '''// h值,可以通過設置jdk的AutoBoxCacheMax參數調整(以下有解釋),自動緩存區間設置為[-128,N]。注意區間的下界是固定''' int h = 127; if (integerCacheHighPropValue != null) { '''// Use Long.decode here to avoid invoking methods that''' '''// require Integer's autoboxing cache to be initialized''' // 通過解碼integerCacheHighPropValue,而得到一個候選的上界值''' int i = Long.decode(integerCacheHighPropValue).intValue(); '''// 取較大的作為上界,但又不能大于Integer的邊界MAX_VALUE''' i = Math.max(i, 127); '''// Maximum array size is Integer.MAX_VALUE''' h = Math.min(i, Integer.MAX_VALUE - -low); } high = h; '''//上界確定''' '''// 就可以創建緩存塊,注意緩存數組大小''' cache = new Integer[(high - low) + 1]; // int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); '''// -128到high值逐一分配到緩存數組''' } private IntegerCache() {} }通過這兩段代碼可以看出,在通過valueof方法創建Integer類型對象時,取值范圍為[-128,127],數值在這個區間里,指針指向IntegerCache.cache中已經存在的對象引用,當數值超出這個范圍,就會創建一個新的對象。
有一點需要注意的是,并不是所有的類型都是這個范圍,看Double類型:
public class Main{ public static void main(String[] args){ Double i1 = 100.0; Double i2 = 100.0; Double i3 = 200.0; Double i4 = 200.0; System.out.println(i1==i2); System.out.println(i3==i4); }}最終的輸出結果:
false
false
具體為什么回事這樣的結果,大伙可以去看看源代碼中Double valueof方法的實現,其和Integer valueof方法不同,是因為在某個范圍內的整型數值的個數是有限的,而浮點數卻不是。
注意,Integer、Short、Byte、Character、Long這幾個類的valueOf方法的實現是類似的。
Double、Float的valueOf方法的實現是類似的。
拉下了一個,Boolean類型的結果有兩個True or False。直接看源代碼:
public static Boolean valueOf(boolean b) { return (b ? TRUE : FALSE); }而其中的TRUE和FALSE是這樣定義的:
public static final Boolean TRUE = new Boolean(true);'''/** ''''''* The <code>Boolean</code> object corresponding to the primitive ''''''* value <code>false</code>. ''''''*/'''public static final Boolean FALSE = new Boolean(false);
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答