Designing a Good Custom Key for HashMap - equal() , hashcode() implementation example
Designing a Good Custom Key for HashMap Can we use an object as a key for a HashMap in Java? This is a very popular interview question indeed. It is asked immediately after “how a HashMap works?”. Let’s make reasoning around a user-defined class as a key in hashmap in Java . Table Of Contents 1. The Key should Honor the Contract between hashCode() and equals() 2. What if Changing the Key’s HashCode is Allowed? 3. We should Make the HashMap’s Key Immutable 4. HashMap Custom Key Example 5. Demo 6. Conclusion 1. The Key should Honor the Contract between hashCode() and equals() The very basic need for designing a good key is that “ we should be able to retrieve the value object back from the map without failure “, otherwise no matter how fancy data structure you build, it will be of no use. To decide that we have created a good key, we MUST know “ how HashMap works? “. I will leave, how hashmap works, part to you to read from the l...