【神奇現象】java整型數的神奇內部快取類
阿新 • • 發佈:2018-11-01
一、常量與物件的比較
這樣的程式碼結果會是什麼?
int a = 1000,b=1000;
System.out.println(a == b);//1
Integer c = 1000, d = 1000;
System.out.println(c == d);//2
結果是:
true
false
知識點:大家都知道這其實是一個常量比較,一個是物件之間比較。根本是比較的指向地址.
然而把上述的數字改為100,結果還會這樣嗎
int a = 100,b=100;
System.out.println(a == b);//1
Integer c = 100, d = 100;
System.out.println(c == d);//2
結果是:
true
true
這裡是不是出現了神奇之處了呢(有趣~~哈哈哈)
原因就是,檢視Integer原始碼會發現有一個內部快取類IntegerCache ,它快取了一定範圍的數(Integer127 ~ -128會存在一個快取裡)
下面程式碼來自Integer類裡
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
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) {
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 IntegerCache() {}
}
還有一段valueof方法
/**
* 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);
}
所以事情就成了,所有的小整數在內部快取,然後當我們宣告類似——
Integer c = 100;
的時候,它實際上在內部做的是
Integer i = Integer.valueOf(100);
類似的Long、Bety 裡面都有類似的快取類。
以上都是自己見解,如有誤,請大家多多指教
參考 :https://blog.csdn.net/xlgen157387/article/details/51261859