奇怪的Java題:爲什麼1000 == 1000返回爲False,而100 == 100會返回爲True?.txt
Integer.java
IntegerCache.java這個內部私有類,它爲-128到127之間的所有整數對象提供緩存。
Integer c = 100;
Integer i = Integer.valueOf(100);
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i<=127
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Integer.valueOf()方法基於減少對象創建次數和節省內存的考慮,緩存了[-128,127]之間的數字。
此數字範圍內傳參則直接返回緩存中的對象。在此之外,直接new出來。
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
private static class IntegerCache {
private IntegerCache(){}
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Integer(i - 128);
}
}
這是因爲在這個範圍內的小數值整數在日常生活中的使用頻率要比其它的大得多,多次使用相同的底層對象這一特性可以通過該設置進行有效的內存優化。你可以使用reflection API任意使用這個功能。
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Class cache = Integer.class.getDeclaredClasses()[0]; //1
Field myCache = cache.getDeclaredField("cache"); //2
myCache.setAccessible(true);//3
Integer[] newCache = (Integer[]) myCache.get(cache); //4
newCache[132] = newCache[133]; //5
int a = 2;
int b = a + a;
System.out.printf("%d + %d = %d", a, a, b); //
}
*** 總結:我們可以給經常用的數字或字符設置緩存,節約內存 ***