Java – using HashMap and custom keys
Quick question: if I want to use a HashMap with a custom class as a key, do I have to override the hashcode function? How will it work if I don't override this feature?
Solution
Technically, you don't have to override the hashcode method as long as equal objects have the same hashcode
Therefore, if you use the default behavior defined by object, where equals returns true only for the same instance, you do not have to override the hashcode method
But if you don't override the equals and hashcode methods, that means you have to make sure you always use the same key instance
For example:
MyKey key1_1 = new MyKey("key1"); myMap.put(key1_1,someValue); // OK someValue = myMap.get(key1_1); // returns the correct value,since the same key instance has been used; MyKey key1_2 = new MaKey("key1"); // different key instance someValue = myMap.get(key1_2); // returns null,because key1_2 has a different hashCode than key1_1 and key1_1.equals(key1_2) == false
In fact, you usually have only one key instance, so technically, you don't have to override the equals and hashcode methods
However, the best practice is to override the equals and hashcode methods of the class used as the key, because sometimes you or other developers may forget that you must use the same instance, which may lead to difficult tracking problems
Please note: even if you override the equals and hashcode methods, you must ensure that the key object is not changed by changing the results of the equals or hashcode methods, otherwise the mapping will not find your value This is why it is recommended to use immutable objects as keys whenever possible