Are immutable objects (other than String
like Integer
and other wrapper classes etc.) good for hashmap keys?
Can anybody explain how?
Are immutable objects (other than String
like Integer
and other wrapper classes etc.) good for hashmap keys?
Can anybody explain how?
If immutable, the object's hashcode wont change and it allows caching the hashcode of different keys which makes the overall retrieval process very fast. Also for mutable objects ,the hashCode() might be dependent on fields that could change, if this happens you wont be able to find the key (and its value) in the HashMap since hashCode() returns different value.
You can find the answer here: How HashMap works in Java
String, Integer and other wrapper classes are natural candidates of HashMap key, and String is most frequently used key as well because String is immutable and final,and overrides equals and hashcode() method. Other wrapper class also shares similar property. Immutabiility is required, in order to prevent changes on fields used to calculate hashCode() because if key object return different hashCode during insertion and retrieval than it won't be possible to get object from HashMap. Immutability is best as it offers other advantages as well like thread-safety, If you can keep your hashCode same by only making certain fields final, then you go for that as well. Since equals() and hashCode() method is used during retrieval of value object from HashMap, its important that key object correctly override these methods and follow contact. If unequal object return different hashcode than chances of collision will be less which subsequently improve performance of HashMap.
There is also another stack for the discussion: Why are immutable objects in hashmaps so effective
Both hashcode and equals method are used in put and get method of HashMap. You need to make sure you can always get the value object from the map after you put it with the key object. No matter you change the key object or not. But Immutable object is good enough to achieve that.
yes because it is unchangeable.
Lets assume that i am having one class
MyKey key = new MyKey("shreyansh"); //assume hashCode=1234
myHashMap.put(key, "value");
// Below code will change the key hashCode() and equals()
// but it's location is not changed.
key.setName("jogi"); //assume new hashCode=7890
//below will return null, because HashMap will try to look for key
//in the same index as it was stored but since key is mutated,
//there will be no match and it will return null.
myHashMap.get(new MyKey("shreyansh"));
here while accessing that using key "Shreyansh" it will return nulll
If you object is immutable and implements hashcode/equals correctly, you are fine to use them as keys in a hashmap.