InterviewSolution
| 1. |
You have an employee class having members as first name and last name. Objects of this employee class need to be added as a key in a hashmap. What all needs to be done to achieve this? |
|
Answer» A HashMap is an unordered collection of key-value pairs. Each key in the hashmap must be unique. The underlying IMPLEMENTATION can be considered to be an Array of Buckets/Nodes where each Node represents a LINKEDLIST. When an element is added to a Hashmap, the hashcode of the key is generated using Hashing. Hashing is the process of converting an object to an integer form. Using the hashcode, the bucket where the key should go to is determined. The list at that bucket is then traversed to determine if the key already exists or not. If the key doesn’t EXIST, the element is added to the LinkedList, else the existing key’s value is updated. In our case, a key is an object of the employee CLASS. To use employee object as a key we need to ENSURE that it can be looked up and its uniqueness can be determined. To achieve this we need to override hashcode() and equals() method. The hashcode() should be written such that the same key will always go to the same bucket. Fro this we can concatenate first name and last name and return hashcode of a concatenated string. In the bucket, the equals() method is used to compare if the two employee objects are the same or not. For this, we can compare the objects both first and last names for equalness. One of the key points to note is that if hashcode of two objects is the same, they might or might not be equal. But if the two objects are equal then their hashcode must be same. |
|