Java 基礎 - 比較方式選擇(什么類型用equals()比較,什么類型用==比較)


ref: https://www.cnblogs.com/lori/p/8308671.html

在 java 中進行比較,我們需要根據比較的類型來選擇合適的比較方式:

  1. 對象域,使用 equals 方法 。

  2. 類型安全的枚舉,使用 equals 或== 。

  3. 可能為 null 的對象域 : 使用 == 和 equals 。

  4. 數組域 : 使用 Arrays.equals 。

  5. 除 float 和 double 外的原始數據類型 : 使用 == 。

  6. float 類型: 使用 Float.foatToIntBits 轉換成 int 類型,然后使用==。

  7. 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.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM