Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't Java have an interface similar to Comparator, but for hashing?
    primarykey
    data
    text
    <p>In Java, the Comparator interface allows a client to specify an equals() and compare() method for any type. A Comparator can be passed to most (or maybe all) collections that require sorting, and the methods in the Comparator will be used instead of the methods of the specified class. This allows clients to sort objects in a way that is different from their natural ordering, or even to sort objects that don't have a natural ordering (i.e. don't implement Comparable).</p> <p>Why isn't there a similar interface for hashing? It could specify two methods, hashCode() and equals(), and be useful for HashSets or HashMaps in the same way Comparators are useful for sorting.</p> <p>Edit: For those who marked this question a duplicate of <a href="https://stackoverflow.com/questions/12132880/why-there-is-no-hashable-interface-in-java">this other question</a>, I would mention that the other question asks why hashCode is included in every class instead of an interface, while this question is about abstracting the hashing function to allow multiple implementations of it.</p> <p>Answer Edit: The best methods of getting this functionality seem to be:</p> <p>-If you're ok using an external library and/or are already using Guava (which is a fantastic library for a lot of reasons), Guava has an <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Equivalence.html" rel="nofollow noreferrer">Equivalence</a> class that allows this.</p> <p>-If you don't want to use an external library, you can use a custom built adapter, similar to what is done in the top answer on <a href="https://stackoverflow.com/questions/15094818/compare-two-java-collections-using-comparator-instead-of-equals">this SO question</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload