Why String class is popular key in a HashMap in Java?


A map is a collection in Java which stores key value pairs. The keys of this must not be null and each key should point to only one value. It is represented by the Map interface of java.util package. There are various classes which provides implementation to this interface.

The HashMap is a class which implements the Map interface. It is based on the Hash table. It allows null values and null keys.

In short, you can store key value pairs in the HashMap object. Once you do so you can retrieve the values of the respective keys but, the values we use for keys should be unique.

Example

import java.util.HashMap;
import java.util.Scanner;
public class HashMapExample {
   public static void main(String args[]) {
      HashMap<String, Long> map = new HashMap<String, Long>();
      System.out.println("Enter the number of records you need to store: ");
      Scanner sc = new Scanner(System.in);
      int num = sc.nextInt();
      for(int i=0; i<num; i++) {
         System.out.println("Enter key (String): ");
         String key = sc.next();
         System.out.println("Enter value (Long): ");
         long value = sc.nextLong();
         map.put(key, value);
      }
      System.out.println("Values Stored . . . . . .");
      System.out.println("Enter a name (key): ");
      String reqKey = sc.next();
      System.out.println("Phone number (value): "+map.get(reqKey));
   }
}

Output

Enter the number of records you need to store:
3
Enter key (String):
Krishna
Enter value (Long):
9848022337
Enter key (String):
Vishnu
Enter value (Long):
9848022338
Enter key (String):
Moksha
Enter value (Long):
9848022339
Values Stored . . . . . .
Enter a name (key):
Krishna
Phone number (value): 9848022337

String is as a key of the HashMap

When you create a HashMap object and try to store a key-value pair in it, while storing, a hash code of the given key is calculated and its value is placed at the position represented by the resultant hash code of the key.

When you pass the key to retrieve its value, the hash code is calculated again, and the value in the position represented by the hash code is fetched (if both hash codes are equal).

Suppose we used a certain variable as key to store data and later we modified the value of this variable. At the time of retrieval, since we changed the key, the hash code of the current key will not match with the hashCode at which its value has been stored making the retrieval impossible.

Since the String class is immutable, you cannot modify the value of a String once it is created. Therefore, it is recommended to use a String variable to hold keys in hash a map.

raja
Published on 01-Aug-2019 12:39:20
Advertisements