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:
Java
// HashMap is available in util package import java.util.HashMap; import java.util.Iterator; import java.util.Map; // Scanner is needed to get inputs and // it is also in util package import java.util.Scanner; public class StringHashMapExample { public static void main(String args[]) { HashMap<String, Long> hashMapOfUsers = new HashMap<String, Long>(); System.out.println( "How many person details containing phone" "numbers are going to get stored: " ); Scanner scanner = new Scanner(System.in); int phoneNumber = scanner.nextInt(); for ( int i = 0 ; i < phoneNumber; i++) { System.out.println( "Enter User Name [key (String)]: " ); String key = scanner.next(); System.out.println( "Enter Phone Number [value (Long)]: " ); long value = scanner.nextLong(); // Let us store key values as // lower case hashMapOfUsers.put(key.toLowerCase(), value); } System.out.println( "Get the details of users . . . . . ." ); Iterator hmIterator = hashMapOfUsers.entrySet().iterator(); // Iterating through Hashmap while (hmIterator.hasNext()) { Map.Entry hashMapElement = (Map.Entry)hmIterator.next(); // Printing mark corresponding // to string entries System.out.println(hashMapElement.getKey() + " : " + hashMapElement.getValue()); } System.out.println( "Enter a name to search in the hashmap(key): " ); String reqKey = scanner.next(); // To avoid case mismatch of user names, // it is converted to lower case System.out.println( "Phone number (value): " + hashMapOfUsers.get(reqKey.toLowerCase())); } } |
Output:
Why “String” is a popular HashMap Key in java?
1. Hashcode:
- 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
2. Immutability:
- 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.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!