Why we should use immutable classes provided by Java as key elements in a Map. It is recommended to use immutable classes as a key in Map. I want to know why?
Asked
Active
Viewed 191 times
0
-
`Why we should use...`, who says that? – KunLun Jul 20 '20 at 16:20
-
If you will be able to change the key of hashMap , how will you get the value of the data , when you do hashMap.get("key") . To further understand this , you need to know the internal implementation of the hashmap . check this https://www.thetechnojournals.com/2019/10/why-hashmap-key-should-be-immutable-in.html – Harmandeep Singh Kalsi Jul 20 '20 at 16:20
-
1This is a closer duplicate: https://stackoverflow.com/questions/20212440/immutable-objects-and-hashmap-keys (I closed this question as a duplicate of a less precise match; perhaps someone else can close it as a duplicate of this one.) – erickson Jul 20 '20 at 16:24
1 Answers
3
You for a key is that its methods Object::hashCode
& Object::equals
shall not change over time otherwise the map will not be able to find the data back.
So if you use a mutable type AND you actually change the key while the data is in the map, then the data will not be found again.
You can put mutable data as key in a map just fine as long as they are not mutated while inside the map. But as a best practice it is better to put immutable data structure as key as to limit the risks of bugs occuring.

Basil Bourque
- 303,325
- 100
- 852
- 1,154

Nicolas Bousquet
- 3,990
- 1
- 16
- 18