當我們給一個 Integer 對 象賦一個 int 值的時候,會調用 Integer 類的靜態方法 valueOf,如果看看 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);
}
而IntegerCache.cache[],裏面就是默認的緩存值,所以,就出現了,如下結果:
Integer t1 = 23;
Integer t2 = 23;
Integer t3 = 223;
Integer t4 = 223;
System.out.println(t1 ==t2);// true
System.out.println(t3 ==t4);// false