ref: https://www.cnblogs.com/lori/p/8308671.html
在 java 中進行比較,我們需要根據比較的類型來選擇合適的比較方式:
-
對象域,使用 equals 方法 。
-
類型安全的枚舉,使用 equals 或== 。
-
可能為 null 的對象域 : 使用 == 和 equals 。
-
數組域 : 使用 Arrays.equals 。
-
除 float 和 double 外的原始數據類型 : 使用 == 。
-
float 類型: 使用 Float.foatToIntBits 轉換成 int 類型,然后使用==。
-
double 類型: 使用 Double.doubleToLongBit 轉換成 long 類型,然后使用==。
至於6)、7)為什么需要進行轉換,我們可以參考他們相應封裝類的 equals() 方法,下面的是 Float 類的:
public boolean equals(Object obj) { return (obj instanceof Float) && (floatToIntBits(((Float)obj).value) == floatToIntBits(value)); }
原因嘛,里面提到了兩點:
However, there are two exceptions:
If f1 and f2 both represent Float.NaN, then the equals method returns true, even though Float.NaN==Float.NaN has the value false. If <code>f1 represents +0.0f while f2 represents -0.0f, or vice versa, the equal test has the value false, even though 0.0f==-0.0f has the value true.