Using Custom Classes as Keys in HashMaps
Today, we are going to discuss what we need to keep in mind when we want to use our custom class as a key in HashMap.
Here, we are considering an Employee class as a key having Id, Name, DateOfBirth, Salary as the properties.
Problem Statement 1
Let's consider the implementation below of the Employee class:
Let's consider using the above class as a HashMap key. For the value element for the HashMap, we are choosing a string for this example:
Solution for Problem Statement 1
The problem was that the hashcode and the Equals method qwew generated from the Object class. employee1 and employee2's generated hashcode will be different, and two Employee objects will be present in the HashMap.
By making the Employee class implement the Object class's equals and hashcode methods, both the employee1 and employee2 hashcode and equals methods will return the same thing.
The HashMap will use the hashcode and equals method to identify the bucket where the object is present and equals to check that the properties values are same. It's going to retrieve the correct value.
Equals and hashcode implementation in the Employee class:
Problem Statement 2
Employee is a mutable object. That will create problems with a HashMap. Let's look at the code below:
Once the Employee Object is mutated, the hashcode of that object is going to change. Now, if we try to retrieve it in step 3 (with the different hashcode), it will go to a different bucket and not be able to get the value. Now, the object placed in the HashMap is lost forever.
Solution for Problem Statement 2
Make the Key object immutable so that mutation of the key will not affect the key element of the HashMap, so the HashMap will be consistent. Below is the implementation of an immutable Employee class via with Builder pattern.
Now update the code of the test to see if the HashMap works consistently:
No comments:
Post a Comment