我們知道基本數據類型包括byte, short, int, long, float, double, char, boolean,對應的包裝類分別是Byte, Short, Integer, Long, Float, Double, Character, Boolean。關於基本數據類型的介紹可參考Java基礎(一) 八大基本數據類型
那么為什么需要包裝類?
JAVA是面向對象的語言,很多類和方法中的參數都需使用對象,但基本數據類型卻不是面向對象的,這就造成了很多不便。
如:List<int> = new ArrayList<>();
,就無法編譯通過
為了解決該問題,我們引入了包裝類,顧名思義,就是將基本類型“包裝起來“,使其具備對象的性質,包括可以添加屬性和方法,位於java.lang包下。
拆箱與裝箱
既然有了基本數據類型和包裝類,就必然存在它們之間的轉換,如:
public static void main(String[] args) {
Integer a = 0;
for(int i = 0; i < 100; i++){
a += i;
}
}
將基本數據類型轉為包裝類的過程叫“裝箱”;
將包裝類轉為基本數據類型的過程叫“拆箱”;
自動拆箱與自動裝箱
Java為了簡便拆箱與裝箱的操作,提供了自動拆裝箱的功能,這極大地方便了程序員們。那么到底是如何實現的呢?
上面的例子就是一個自動拆箱與裝箱的過程,通過反編譯工具我們得到,
public static void main(String[] args) {
Integer a = Integer.valueOf(0);
for (int i = 0; i < 100; i++) {
a = Integer.valueOf(a.intValue() + i);
}
}
我們不難發現,主要調用了兩個方法,Integer.intValue() 和 Integer.valueOf( int i) 方法
查看Integer源碼,我們找到了對應代碼:
/**
* Returns the value of this {@code Integer} as an
* {@code int}.
*/
public int intValue() {
return value;
}
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
很明顯,我們我們得出,Java幫你隱藏了內部細節。
拆箱的過程就是通過Integer 實體調用intValue()方法;
裝箱的過程就是調用了 Integer.valueOf(int i) 方法,幫你直接new了一個Integer對象
那么哪些地方會進行自動拆裝箱?
其實很簡單
1.添加到集合中時,進行自動裝箱
2.涉及到運算的時候,“加,減,乘, 除” 以及 “比較 equals,compareTo”,進行自動拆箱
注意的點
在上述的代碼中,關於Integer valueOf(int i)方法中有IntegerCache類,在自動裝箱的過程中有個條件判斷
if (i >= IntegerCache.low && i <= IntegerCache.high)
結合注釋
This method will always cache values in the range -128 to 127,
inclusive, and may cache other values outside of this range.
大意是:該方法總是緩存-128 到 127之間的值,同時針對超出這個范圍的值也是可能緩存的。
那么為什么可能緩存?其實在IntegerCache源碼中可以得到答案
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.
}
}
因為緩存最大值是可以配置的。這樣設計有一定好處,我們可以根據應用程序的實際情況靈活地調整來提高性能。
與之類似還有:
Byte與ByteCache,緩存值范圍-128到127,固定不可配置
Short與ShortCache,緩存值范圍-128到127,固定不可配置
Long與LongCache,緩存值范圍-128到127,固定不可配置
Character與CharacterCache,緩存值范圍0到127,固定不可配置