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.

猜你喜欢

转载自www.cnblogs.com/frankcui/p/10810672.html
今日推荐