Why is BigDecimal natural ordering inconsistent with equals?

后端 未结 4 1517
感情败类
感情败类 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 19:59

    The behaviour seems reasonable in the context of arithmetic precision where trailing zeros are significant figures and 1.0 does not carry the same meaning as 1.00. Making them unequal seems to be a reasonable choice.

    However from a comparison perspective neither of the two is greater or less than the other and the Comparable interface requires a total order (i.e. each BigDecimal must be comparable with any other BigDecimal). The only reasonable option here was to define a total order such that the compareTo method would consider the two numbers equal.

    Note that inconsistency between equal and compareTo is not a problem as long as it's documented. It is even sometimes exactly what one needs.

提交回复
热议问题