曾經遇見過一道關於Integer的面試題:
Integer a = 180, b = 180;
Integer c=1,d=1;
System.out.println(a==b);
System.out.println(c==d);
輸出爲:
false
true
一開始也不明白,後來看了下Integer的源碼,才知道Integer默認將-128~127之間的整數存儲到了一個數組中,我們使用的時候,直接調用數組中數據,而超過這個範圍就會重新創建Integer對象,看下源代碼就明白了
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 =
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 static void swap(Integer a, Integer b) {
Integer temp = a;
a = b;
b = temp;
}
一開始,我認爲應該是傳遞的引用,調用後,應該會發生數據值的改變,但事實上數據卻並沒有發生交換。那就繼續看代碼吧
/**
* 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
*/
@HotSpotIntrinsicCandidate
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
/**
* The value of the {@code Integer}.
*
* @serial
*/
private final int value;
看到這裏我們也就明白了,我們的數據值保存在value這個私有常量值中,當兩個值交換時,因爲Integer的自動拆裝箱導致傳遞的是數據值,也就是值傳遞,因此不會修改原值。想要交換兩個Integer對象的值應該通過修改這個value值來實現,因此我們可以通過反射獲取這個私有的value屬性然後進行修改
private static void swap1(Integer a, Integer b) {
try {
Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
int temp = a.intValue();
field.set(a, b.intValue());
field.set(b,temp);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
測試下,發現還是不對,原來field.set()這個方法傳入的是對象, field.set(a, b.intValue())這個方法中,b.intValue()相當於Integer.valueOf(a.intValue()).intValue(),而temp只是int,因此並沒有修改b中的value值,好,繼續改
private static void swap1(Integer a, Integer b) {
try {
Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
Integer temp = Integer.valueOf(a.intValue());
field.set(a, b.intValue());
field.set(b,temp);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
我們通過反射機制獲取Integer屬性值value,然後用a的值重新創建一個對象,這樣我們傳遞的就是一個地址值,從而實現真正的交換
注意
以前創建Integer對象的時候,我們都是直接new出來,但是先java已經廢棄了這個方法,查看文檔發現改爲使用Integer.valueOf()方法,查看valueOf方法我們知道,由於-128~127緩存存在,當我們用第一種方式時每次都會產生一個新的實例,而當你使用靜態工廠方法時,不一定會產生一個新的實例,所以這樣是現在推薦使用valueOf()這個方法的原因吧
總結
通過這個問題的分析,我們主要涉及到Integer的拆裝箱、通過反射機制去修改privat final value、Integer的-128~127的緩存,其他的問題我們以後再研究吧