標籤:ash 設定 stat 三目運算 html out integer 資料類型 final
# java 自動裝箱、拆箱
從 jdk 1.5 版本開始, 引入該功能。
一、自動裝箱
將基礎資料型別 (Elementary Data Type)自動封裝為對應封裝類。
程式碼範例,
Integer i = 100;
100屬於基本類型int,會自動裝箱,如下:
Integer i = Integer.valueOf(100);
相當於,
Integer i = new Integer(100);
二、自動拆箱
將封裝類自動轉換為對應的基礎資料型別 (Elementary Data Type)。
程式碼範例,
Integer i = new Integer(100);int j = i;
i屬於封裝類Integer,會自動拆箱,如下:
Integer i = new Integer(100);int j = i.intValue();
三、問題
問題代碼(會引起NPE問題),
Map<String, Boolean> map = new HashMap<String, Boolean>();Boolean b = (map != null ? map.get("test") : false);
問題原因:三目運算子第二、三運算元類型不同(一個為對象,一個為基礎資料型別 (Elementary Data Type)),會將對象自動拆箱為基礎資料型別 (Elementary Data Type)。
拆箱過程,
Map<String, Boolean> map = new HashMap<String, Boolean>();Boolean b = Boolean.valueOf(map != null ? map.get("test").booleanValue() : false);
問題解決,
Map<String, Boolean> map = new HashMap<String, Boolean>();Boolean b = (map != null ? map.get("test") : Boolean.FALSE);
相關代碼,
Integer int1 = 100;Integer int2 = 100;Integer int3 = 300;Integer int4 = 300; // trueSystem.out.println(int1 == int2);// falseSystem.out.println(int3 == int4);
引起問題原因:裝箱調用了Integer.valueOf()。源碼如下,
public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i);}
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) { 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); } 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() {}}
未進行特別設定,IntegerCache.high取值為127。因此,通過Integer.valueOf()方法建立Integer對象的時候,如果數值在[-128,127]之間,返回IntegerCache.cache中對象的引用,否則建立一個新的Integer對象。
java 自動裝箱、拆箱