A library for implementing equals and hashCode

Kevin Bourrillion kevinb at google.com
Thu Apr 25 21:42:11 UTC 2019

On Tue, Apr 23, 2019 at 3:40 PM Liam Miller-Cushon <cushon at google.com>

There's some related discussion under "What’s the relationship to
> Comparator?". There are at least four options: Equivalence extends
> Comparator, Comparator extends Equivalence, there's no relationship between
> them, or they both extend some new common super type. There are trade-offs
> here, but none of those options seem like a slam-dunk.

As I'm looking at it, 1 and 2 basically just don't work; neither
generalizes the other. If it's option 3, no relationship, there is still
the possibility that a common set of factory methods will produce a thing
that implements both, or that a common builder could have methods for
producing each. And yeah, *some* way to unify the two is at least
*somewhat* desirable, because we really, really like it when people using
TreeSets follow TreeSet's advice to keep their comparison logic consistent
with equals, and this would help them do that.

However, this has the potential to raise the perceived complexity of the
resulting beast and I think it's far from clear that it'll end up worth it.
I also think that just being able to construct your comparison and equality
logic in consistent and concise ways that you can review against each other
gets us at least 51% of the way there.

> On Mon, Apr 22, 2019 at 12:20 PM Fred Toussi <fredt at users.sourceforge.net>
> wrote:
>> Since 2014 HSQLDB has been using an ObjectComparator that extends
>> Comparator for its hash sets and maps. These are sets and maps for
>> combinations of int, long and Object, as well as order preserving sets and
>> maps.
>> https://sourceforge.net/p/hsqldb/svn/HEAD/tree/base/trunk/src/org/hsqldb/lib/ObjectComparator.java
>> https://sourceforge.net/p/hsqldb/svn/HEAD/tree/base/trunk/src/org/hsqldb/map/BaseHashMap.java
>> We made a shortcut to extend Comparator, but if this is going to be added
>> to Java, your Equivalence<T> should be the super interface of Comparator<T>
>> You may also consider the problems of correctly implementing equals in
>> subclasses, which took years to be clarified (by Martin Odersky AFAIR) by
>> calling super.equals(other) before performing the test. Example below from
>> HSQLDB code.
>>     public class RowType extends Type {
>>     public boolean equals(Object other) {
>>         if (other == this) {
>>             return true;
>>         }
>>         if (other instanceof RowType) {
>>             if (super.equals(other)) {
>>             ....
>> Regards
>> Fred Toussi
>> HSQLDB Project

Kevin Bourrillion | Java Librarian | Google, Inc. | kevinb at google.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20190425/34633c89/attachment.html>

More information about the amber-spec-experts mailing list