這篇文章主要介紹Integer IntegerCache源碼的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
創(chuàng)新互聯(lián)公司服務(wù)項目包括競秀網(wǎng)站建設(shè)、競秀網(wǎng)站制作、競秀網(wǎng)頁制作以及競秀網(wǎng)絡(luò)營銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢、行業(yè)經(jīng)驗、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,競秀網(wǎng)站推廣取得了明顯的社會效益與經(jīng)濟效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到競秀省份的部分城市,未來相信會繼續(xù)擴大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!
先看一段測試結(jié)果:
/*public static void main(String[] args) { Integer a = 128, b = 128; Integer c = 127, d = 127; System.out.println(a == b);//false System.out.println(c == d);//true }*/ /*public static void main(String[] args) { Integer int1 = Integer.valueOf("100"); Integer int2 = Integer.valueOf("100"); System.out.println(int1 == int2);//true }*/ public static void main(String[] args) { Integer int1 = Integer.valueOf("300"); Integer int2 = Integer.valueOf("300"); System.out.println(int1 == int2);//false }
JDK的源碼如下:
public static Integer valueOf(String s) throws NumberFormatException { return Integer.valueOf(parseInt(s, 10)); } public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
發(fā)現(xiàn)里面另有玄機,多了個IntegerCache類:
private static class IntegerCache { static final int low = -128; static final int high; static final Integer cache[]; static { // high value may be configured by property int 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_VALUE h = 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把-128到127(可調(diào))的整數(shù)都提前實例化了。
這就解釋了答案,原來你不管創(chuàng)建多少個這個范圍內(nèi)的Integer用ValueOf出來的都是同一個對象。
但是為什么JDK要這么多此一舉呢? 我們仔細想想, 淘寶的商品大多數(shù)都是100以內(nèi)的價格, 一天后臺服務(wù)器會new多少個這個的Integer, 用了IntegerCache,就減少了new的時間也就提升了效率。同時JDK還提供cache中high值得可配置,
這無疑提高了靈活性,方便對JVM進行優(yōu)化。
以上是“Integer IntegerCache源碼的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
網(wǎng)站題目:IntegerIntegerCache源碼的示例分析
鏈接分享:http://aaarwkj.com/article44/iipiee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、關(guān)鍵詞優(yōu)化、用戶體驗、定制開發(fā)、小程序開發(fā)、品牌網(wǎng)站設(shè)計
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)