Why is BigDecimal natural ordering inconsistent with equals?

后端 未结 4 1520
感情败类
感情败类 2020-12-13 19:32

From the Javadoc for BigDecimal:

Note: care should be exercised if BigDecimal objects are used as keys in a SortedMap or ele

4条回答
  •  醉话见心
    2020-12-13 20:03

    The answer is pretty short. equals() method compares objects while compareTo() compares values. In case of BigDecimal different objects can represent same value. Thats why equals() might return false, while compareTo() returns 0.

    equal objects => equal values

    equal values =/> equal objects

    Object is just a computer representation of a some real world value. For example same picture might be represented in a GIF and JPEG formats. Thats very like BigDecimal, where same value might have distinct representations.

提交回复
热议问题