Java 128陷阱+自动装箱拆箱
1.大綱概述
????????Int 整型為java八大基礎類型之一,Integer是它的包裝器類型;int的默認值為0,而Integer的默認值為null。
????????128陷阱:指 Integer類封裝的數字在[-128,127]范圍內比較可以相等,超過此范圍不能相等的現象。如下為代碼示例:
public static void main(String[] args) {Integer a = 127;Integer b = 127;Integer c = 128;Integer d = 128;Integer e= -129;Integer f= -129;System.out.println(a==b);System.out.println(c==d);System.out.println(e==f); }輸出:
true false false? ? ? ? 自動裝箱:int到Integer的變換稱為裝箱(自動將基本數據類型轉換為包裝器類型),當有一個Integer對象賦予給int將會自動拆箱,而Integer的自動裝箱要求數據介于-128~127之間。
Integer a=Integer.valueOf(100);????????自動拆箱:Integer到Int的變換稱為拆箱(自動將包裝器類型轉換為基本數據類型)
int d=c.intValue()*1-100;2、代碼分析
IntegerCache.low 和IntegerCache.high是“128陷阱”的關鍵。java對在-128~127之間的Integer的值,用原生數據類型int,會在內存里供重用,也就是說這之間的Integer值進行 == 比較時只是進行int原生數據類型數值比較,超出-128~127的范圍,進行 == 比較時是進行地址比較。(引用類型用 == 比較,是對他們的地址進行比較)
Integer 自動裝箱代碼:????????
public static Integer valueOf(int i) {if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);} 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() {}}用兩個等號==相比較時,比較的是valueOf的返回值,可以看出,IntegerCache.low 和IntegerCache.high是“128陷阱”的關鍵。當int i超過某個范圍時,返回一個新的對象,即
return new Integer(i);?否則,如果i在約束的范圍內(范圍很可能時我們上面提到的[-128,127]),返回某個固定地址的值。即
return IntegerCache.cache[i + (-IntegerCache.low)];IntegerCache.low默認是-128;IntegerCache.high默認是127。
如果傳入的 i 在IntegerCache.low 和IntegerCache.high之間,那就嘗試看前面的緩存中有沒有打過包的相同的值,如果有就直接返回,否則就新創建一個Integer實例,此時地址會改變,當進行 ==的比較時會返回false.
?
總結
以上是生活随笔為你收集整理的Java 128陷阱+自动装箱拆箱的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 汉字转html实体符号js_html实体
- 下一篇: c语言行列坐标是先行后j,C语言学习之行