Why String is popular HashMap key in Java?
There are many instances when data is stored as key-value pairs. In Java, it can be achieved by “map” which is a collection. Keys usually should not be null and they should point to only one value. In Map, there are various classes available and among them, Hashmap is a class that implements the Map interface.
Hashmap is based on Hashtable. It can allow null values and null keys.
- The main important thing is that the key should be unique and with that unique key, we can retrieve the values quickly.
- First, let us see a sample of storing and displaying the data using Hashmap, and then will see why String is a popular hashmap key in Java!
Let us store a few data of persons containing their mobile numbers:
Why “String” is a popular HashMap Key in java?
- When we store the data using HashMap, a hash code of the given key is calculated, for example, we have given 2 keys in the above example and for them,
- The hashcode is calculated and its value is placed at the position represented by the resultant hash code of the key.
- Similarly while fetching the data, the hash code is again calculated, by this way the value in the position represented by the hash code is retrieved. Always by checking both hash code equality, the value is retrieved.
- Other than String, if we use any other datatype and try to change the value and also key, stored hash value (in the storing time) and retrieved hash value (during fetching time) will definitely vary and hence we cannot retrieve the apt value
- A string is immutable. We cannot modify the value of the string after it got created. This is the main advantage. i.e. hashcode remains the same while storing and also retrieving also. Hence always and also it is a popular approach of using a String variable to hold keys in a hash map.
- Hashcode is cached and no need to calculate again also (as String immutable)
- Immutability is a great mechanism to get same hash code every time, for a key object. Hence always it is ideal to go for String and it solves memory leaks, value unavailability, etc.,
- hashCode() and equals() methods contract is playing around when data is stored in HashMap. String because of immutability provides maximum support for this.
My Personal Notes arrow_drop_up
Please Login to comment...