Equals operator for zeros (BigDecimal / Double) in Java

后端 未结 7 1166
别那么骄傲
别那么骄傲 2020-12-14 06:31

A few interesting observations w.r.t equals operator on 0 and 0.0

  1. new Double(0.0).equals(0) returns false, while new Double(0.0).equals(0

7条回答
  •  心在旅途
    2020-12-14 06:42

    BigDecimal 'equals' compares the value and the scale. If you only want to compare values (0 == 0.0) you should use compareTo:

    BigDecimal.ZERO.compareTo(BigDecimal.valueOf(0.0)) == 0 //true
    BigDecimal.ZERO.compareTo(BigDecimal.valueOf(0)) == 0 //true
    

    See the javadoc.

    As for the Double comparison, as explained by other answers, you are comparing a Double with an Integer in new Double(0.0).equals(0), which returns false because the objects have different types. For reference, the code for the equals method in JDK 7 is:

    public boolean equals(Object obj) {
        return (obj instanceof Double)
               && (doubleToLongBits(((Double)obj).value) ==
                      doubleToLongBits(value));
    }
    

    In your case, (obj instanceof Double) is false.

提交回复
热议问题