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
In Java, there are basically multiple ways:
hashCode()
method you inherit from Object (not a really great option, as that ignores your fields)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.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.