Can you use custom objects as keys in a HashMap? What requirements should the key class meet?

Category : Java | Sub Category : Java Interview questions | By Prasad Bonam Last updated: 2023-08-03 13:46:38 Viewed : 327


Can you use custom objects as keys in a HashMap? What requirements should the key class meet?

Yes, you can use custom objects as keys in a HashMap. To use custom objects as keys effectively, the key class should meet two important requirements:

  1. Correctly implement hashCode(): The hashCode() method must be overridden in the custom key class to provide a unique hash code for each distinct key object. If two key objects are considered equal according to the equals() method, they must produce the same hash code when hashCode() is called on them. This ensures that when you store and retrieve key-value pairs in the HashMap, the correct bucket (index) is used to store and locate the value associated with that particular key.

  2. Properly implement equals(): The equals() method should be correctly implemented to define the notion of equality for key objects. It should determine when two key objects are considered equal. If two key objects are equal according to the equals() method, their hashCode() values must also be the same.

To summarize, the hashCode() and equals() methods should be overridden in the custom key class to ensure proper functioning of the HashMap. Here is an example of a custom key class:

java
public class CustomKey { private int keyField1; private String keyField2; // Constructors, getters, setters, etc. @Override public int hashCode() { // Compute a unique hash code based on the fields that define the key int result = 31 * keyField1; result = 31 * result + (keyField2 != null ? keyField2.hashCode() : 0); return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CustomKey)) return false; CustomKey otherKey = (CustomKey) o; return keyField1 == otherKey.keyField1 && Objects.equals(keyField2, otherKey.keyField2); } }

In this example, the hashCode() method combines the hash codes of the fields keyField1 and keyField2, and the equals() method checks if both fields are equal. This ensures that instances of the CustomKey class will behave correctly when used as keys in a HashMap.

Keep in mind that if you modify the key object after it has been used as a key in the HashMap, its hash code may change, and you may encounter issues when trying to retrieve the corresponding value. Its best to use immutable objects as keys or ensure that the key object remains unchanged during its usage as a key in the HashMap.


Search
Related Articles

Leave a Comment: