Integer缓存池
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                Integer缓存池
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                new Integer(127)和Integer.valueOf(127)是有區(qū)別的:理由如下!
- new Integer(127):每次都會創(chuàng)建一個新的對象。
- Integer.valueOf(127):會使用緩存池中的對象,意味著多次調(diào)用都是同一個地址。
Java8中Integer緩存池的范圍是[-128,127]。意味著在這個范圍內(nèi)的數(shù)值多次使用,都是同一個地址。
Integer.valueOf(int i)的實(shí)現(xiàn):
過程:首先判斷該數(shù)是否在緩存池范圍內(nèi),如果在就從緩存池里面取,否則重新新建一個對象。
public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i); }緩存結(jié)構(gòu):
源碼可以看出該緩存池使用一個數(shù)組實(shí)現(xiàn)的,范圍在[-128,127]之間都是存緩存的。
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() {} }編譯器在自動裝箱的過程中,首先會調(diào)用Integer.valueOf(int i)來創(chuàng)建。如果存在相同值,那么就會使用緩存中相同的地址。
Integer a = 127; Integer b = 127; System.out.println(a == b);//true Integer c = 128; Integer d = 128; System.out.println(c= =d);//false總結(jié)
因?yàn)樘厥庑?#xff0c;所以在開發(fā)中使用該包裝類的時候,如果是比較兩個值是否相等,盡量用equals()來比較。
總結(jié)
以上是生活随笔為你收集整理的Integer缓存池的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: python获取视频时长方法
- 下一篇: Vue封装hbuilder热更新
