int i = 65;
float f = 65.0f;
char c = 'A'; // ASCII 65
System.out.println(i == f); // true:數值相等
System.out.println(c == f); // true:字符自動提升為 int 比較
基本類型之間的 == 會觸發數值提升,本質是數值比較。
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false:不同對象,地址不同
System.out.println(s1.equals(s2)); // true:String 重寫了 equals() 比較字符序列
String 重寫邏輯:先比長度,再逐字符比較,確保內容一致即返回 true。
Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true:命中緩存池
Integer c = 128;
Integer d = 128;
System.out.println(c == d); // false:超出緩存範圍,新建對象
Integer.valueOf(int) 內部實現:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
-XX:AutoBoxCacheMax=size 擴大上限==,引用類型比較內容統一用 equals()== 比較包裝類型,除非確定在緩存範圍內equals() 和 hashCode() 滿足契約"hello" == "hello" 為 true,但 new String("hello") 每次新建對象