Every type is derived from Any, which comes with a hashCode method declaration. This is the equivalent of a Java object class's hashCode method. This method is important when you want to place your instances in a collection, such as a map.
An object's hash code allows algorithms and data structures to place the instances in buckets. Imagine you implement a phone book. You'll place any name that starts with A in the A section, any name that starts with B in the B section, and so on. This simple approach allows you to search for someone quickly. This is how hash-based collections, such as HashMap and HashSet, are implemented.
When implementing the method, you need to adhere to a contract:
- When invoked on the same object more than once during runtime, the hashCode method must consistently return the same value, given...