一个关于Integer的秘密
先讓大家看一段簡單的代碼:
public static voidmain(String[] args) { Integera = 1; Integerb = 1;Integerc = 222; Integerd = 222;System.out.println(a== b); System.out.println(c== d); }大家猜一下。輸出的結果會是什么?我想大多數剛開始學習的人都會覺得是:true??true。
但是,實際呢?正確答案是:true
false。這時,是不是有人開始納悶了,不禁問道:為什么呢?邏輯都一樣,僅僅是數字不同,難道跟數字有關?恭喜你。答對了,確實跟數字有關。以下我就帶大家看看當中的緣由。
?
我們看一下integer源代碼中的兩個方法:
publicstatic Integer valueOf(int i) {if(i >= -128 && i <=IntegerCache.high)return IntegerCache.cache[i + 128];elsereturn new Integer(i);}privatestatic class IntegerCache {static final int high;static final Integer cache[];static {final int low = -128;// high value may be configured bypropertyint h = 127;if (integerCacheHighPropValue !=null) {// Use Long.decode here toavoid invoking methods that// require Integer's autoboxingcache to be initializedint i =Long.decode(integerCacheHighPropValue).intValue();i = Math.max(i, 127);// Maximum array size isInteger.MAX_VALUEh = 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++);}private IntegerCache() {}}
當我們初始化一個integer類型的變量時。如:Integer a = 1。實際上它調用了integer中的valueOf方法,相當于Integera = Integer.valueOf(1),而在這種方法內部有一個緩存的機制。
它會推斷你給變量賦的值是否在-128——127之間。假設是,那么它直接從緩存里去取對象。反之才會新創建一個對象。
也就是說,當程序運行Integerb = 1時。緩存中已經存在這個integer對象,它直接將b指向緩存中的對象,結果就是a、b指向同一對象,而c、d就不同了。它們兩個終于會指向兩個新創建的不同的對象,運行c==d時。自然不會相等。如今大家該明確了吧。
?
明確了這個原理,最重要的還是要應用于實際。當我們在程序中操作小整型數字的時候,我們要充分利用integer中的緩存機制,節省程序創建對象的時間,以此來提高我們程序的效率。
?
最后,假設有人關心==與equal的差別,請看以下這篇文章:
具體解釋java中equals和== 的差別
?
轉載于:https://www.cnblogs.com/ldxsuanfa/p/10567406.html
總結
以上是生活随笔為你收集整理的一个关于Integer的秘密的全部內容,希望文章能夠幫你解決所遇到的問題。