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.

 

posted on   frank_cui  阅读(1233)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

levels of contents
点击右上角即可分享
微信分享提示