學習記錄并且簡單分析
記錄學習遇到的困難,一個小白!
本人基本沒有讀過原始碼,純小白一個,寫這篇文章純屬是為了提高自己!!!希望各位積極指出錯誤,
好奇的我翻看了Integer.valueOf()方法原始碼
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
首先引數解釋:
static final int low = -128;
static final int high;
static final Integer[] cache;
static Integer[] archivedCache;
high沒有賦值,所以我們繼續跟蹤到high屬性
static {
int h = 127;
//啟動時如果指定-Djava.lang.Integer.IntegerCache.high=XXX(自己輸入一個資料)引數
//將會執行下面的陳述句,則動態的設定h是127還是設定的輸入資料
String integerCacheHighPropValue =
https://www.cnblogs.com//該方法是通過傳遞一個key,獲取啟動時手動設定的數值
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
h = Math.max(parseInt(integerCacheHighPropValue), 127);
//
// public static int max(int a, int b) {
// return (a >= b) ? a : b;
// }
// Maximum array size is Integer.MAX_VALUE
//32位系統2147483647=2^32
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
//找到high屬性的值由h區域屬性賦值
high = h;
// Load IntegerCache.archivedCache from archive, if possible
VM.initializeFromArchive(IntegerCache.class);
int size = (high - low) + 1;//可以存256個數,
//至于為啥是256?這里我不講述,建議自己去搜索下計算機存放資料相關的概念!
// Use the archived cache if it exists and is large enough
if (archivedCache == null || size > archivedCache.length) {
Integer[] c = new Integer[size];
int j = low;
//c.length=256
//j=-128
for(int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}
//陣列c對應256個數,c[0]對應-128,c[256]對應127
//很巧妙
archivedCache = c;
}
cache = archivedCache;
// range [-128, 127] must be interned (JLS7 5.1.7)
//斷言,如果最高值小于127拋出例外
assert IntegerCache.high >= 127;
}
現在我們再回到
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
//前面說過設計很巧妙
//i為什么要加上-(-128)?你理解沒!
//原因是因為cache陣列的第0位保存的是-128!
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);//如果不在該范圍,則創建實體
}
現在我們就明白了如果實參在-128到127之間,就會直接去從靜態方法區拿實體物件,這么做是為了減少開銷,
下面驗證
Integer int_instance1 = Integer.valueOf("100");
Integer int_instance2 = Integer.valueOf("100");
System.out.println(int_instance1 == int_instance2);
運行結果是true
Integer int_instance1 = Integer.valueOf("100");
Integer int_instance2 = Integer.valueOf("101");
System.out.println(int_instance1 == int_instance2);
運行結果是false
原因通過下面的表解釋,簡單的畫了一下

Integer int_instance1 = Integer.valueOf("128");
Integer int_instance2 = Integer.valueOf("128");
System.out.println(int_instance1 == int_instance2);
結果是false
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/206666.html
標籤:其他
