首先我們先來看一個代碼,關於Integer通過 ‘=’ 直接賦值:
public class Main {
public static void main(String[] args) {
Integer f1 = 100;
Integer f2 = 100;
Integer f3 = 200;
Integer f4 = 200;
System. out.println( f1 == f2); //true
System. out.println( f3 == f4); //false
}
}
同樣是通過‘=’來賦值爲什麼會有這樣的結果?
答:Integer賦予一個int類型的時候(通過‘=’賦值)會調用Integer的靜態方法valueOf
等同於下面的代碼
public class Main {
public static void main(String[] args) {
Integer f1 = Integer.valueOf(100);
Integer f2 = Integer.valueOf(100);
Integer f3 = Integer.valueOf(200);
Integer f4 = Integer.valueOf(200);
System. out.println( f1 == f2); //true
System. out.println( f3 == f4); //false
}
}
思考:那麼Integer.valueOf()返回的Integer是不是是重新new Integer(num);來創建的呢?如果是這樣的話,那麼== 比較返回都是false,因爲他們引用的堆地址不一樣。
具體來看看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);
}
可以看出來值在一個區間內不會去new一個新的對象;這個範圍規範是-128~127;
那麼不new一個新對象在哪裏取值尼,在IntegerCache中cache數組初始化如下,存入了-128 - 127的值
cache = new Integer[(high - low) + 1];
int j = low;
for( int k = 0; k < cache.length ; k ++)
cache[k] =
cache[k] = new Integer(j ++);
從上面我們可以知道給Interger 賦予的int數值在-128 - 127的時候,直接從cache中獲取,這些cache引用對Integer對象地址是不變的,但是不在這個範圍內的數字,則new Integer(i) 這個地址是新的地址,不可能一樣的.