RFR: 8261123: Augment discussion of equivalence classes in Object.equals and comparison methods [v3]

Stuart Marks smarks at openjdk.java.net
Thu Feb 11 04:49:43 UTC 2021


On Thu, 11 Feb 2021 04:24:40 GMT, Stuart Marks <smarks at openjdk.org> wrote:

>> Joe Darcy has updated the pull request incrementally with one additional commit since the last revision:
>> 
>>   Fix typos in javadoc tags found during review.
>
> src/java.base/share/classes/java/math/BigDecimal.java line 97:
> 
>> 95:  * contrast, the {@link equals equals} method requires both the
>> 96:  * numerical value and representation to be the same for equality to
>> 97:  * hold.
> 
> Note, discussing "representation" is ok here since the context is discussing the representation of BigDecimal (in contrast to the text in Comparable).

It might be reasonable to add a bit of rationale here and give an example. I think the reason that members of the same cohort might not be considered `equals()` to one another is that they are not substitutable. For example, consider 2.0 and 2.00. They are members of the same cohort, because

    new BigDecimal("2.0").compareTo(new BigDecimal("2.00")) == 0

is true. However,

    new BigDecimal("2.0").equals(new BigDecimal("2.00"))

is false. They aren't considered `equals()` because they aren't substitutable, since using them in an arithmetic expression can give different results. For example:

    new BigDecimal("2.0").divide(new BigDecimal(3), RoundingMode.HALF_UP)
    ==> 0.7

    new BigDecimal("2.00").divide(new BigDecimal(3), RoundingMode.HALF_UP)
    ==> 0.67

I think that's the right rationale, and a reasonable example to illustrate it. Edit to taste. I think it would be good to have material like this, though, because people's immediate reaction to BD being inconsistent with equals is "well that's wrong." Well, no, it's right, and I think this is the reason.

-------------

PR: https://git.openjdk.java.net/jdk/pull/2471


More information about the core-libs-dev mailing list