包装类的缓存问题
包裝類的緩存問題
整型、char類型所對應的包裝類,在自動裝箱時,對于-128~127之間的值會進行緩存處理,其目的是提高效率。
緩存處理的原理為:如果數據在-128~127這個區間,那么在類加載時就已經為該區間的每個數值創建了對象,并將這256個對象存放到一個名為cache的數組中。
每當自動裝箱過程發生時(或者手動調用valueOf()時),就會先判斷數據是否在該區間,如果在則直接獲取數組中對應的包裝類對象的引用,如果不在該區間,則會通過new調用包裝類的構造方法來創建對象。
比如以下這個測試程序:
Integer in1 = -128; Integer in2 = -128; System.out.println(in1 == in2);//true 因為123在緩存范圍內 System.out.println(in1.equals(in2));//true出現這樣的原因,可以查看Integer的源碼:
public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);}IntegerCache類為Integer類的一個靜態內部類,僅供Integer類使用,IntegerCache.low為-128,IntegerCache.high為127
緩存了[-128,127]之間的數字。實際就是系統初始的時候,創建了[-128,127]之間,的一個緩存數組。
當我們調用valueOf()的時候,首先檢查是否在[-128,127]之間,如果在這個范圍則直接從緩存數組中拿出已經創建好的對象
如果不在這個范圍,則創建新的Integer對象。
private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[];static {// high value may be configured by propertyint h = 127;String integerCacheHighPropValue =sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");if (integerCacheHighPropValue != null) {try {int i = parseInt(integerCacheHighPropValue);i = Math.max(i, 127);// Maximum array size is Integer.MAX_VALUEh = Math.min(i, Integer.MAX_VALUE - (-low) -1);} catch( NumberFormatException nfe) {// If the property cannot be parsed into an int, ignore it.}}high = h;cache = new Integer[(high - low) + 1];int j = low;for(int k = 0; k < cache.length; k++)cache[k] = new Integer(j++);// range [-128, 127] must be interned (JLS7 5.1.7)assert IntegerCache.high >= 127;}private IntegerCache() {}}再來測試以下:
Integer in3 = 1234; Integer in4 = 1234; System.out.println(in3 == in4);//false 因為1234不在緩存范圍內 System.out.println(in3.equals(in4));//true由于-128在[128,127]范圍內,所以是從cache數組中直接取出創建好的對象,而1234超過了這個范圍,那就直接new一個,導致了in3和in4是兩個不同的對象。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
- 上一篇: PyQt5 参考文档
- 下一篇: PyQt5 笔记5 -- 消息框(QMe