Search code examples
javahashmaphashcodehashable

Does Java have something like Hashable, Hasher?


For Hash data structures, like HashSet, HashMap, etc., we need to implement hashcode. However, this is not very convenient. Can we use something like Hashable or Hasher instead?

Here is an example in Swift: https://developer.apple.com/documentation/swift/hashable


Solution

  • In Java, there are basically multiple ways:

    • you just "keep" the hashCode() method you inherit from Object (not a really great option, as that ignores your fields)
    • you use Objects.hashCode() to compute hashes on fields, to then use that when doing a @Override for hashCode() in a custom class. As pointed out by user Andreas, the one downside of this solution is the auto-boxing detour when using this method for primitive type values.
    • you can also use the Apache Commons HashCodeBuilder. The big advantage: that class automatically uses reflection to retrieve all field values for hashing. The downside: reflection is error prone, and comes with a significant performance impact. But it is still an interesting option, for example when dealing with "data holder" aka "bean classes" that are basically just containers for fields with getters and setters.

    Beyond that: you can of course override hashCode() yourself for each class you need to, and "manually" compute hashes from your fields. Or tell your IDE to do that for you.

    Finally, going one step further, the JVM platform allows for libraries like Lombok that automatically insert such method overrides during the compile phase. Or even to use other languages for the JVM like kotlin with its data classes.