Tuesday 9 February 2016

How HashMap working internally in details (in java)

 Map Interface:- map is interface

A map contains key and value pair.Each pair is known as an entry.
Map contains only unique elements.

Entry

Entry is the subinterface of Map. So we will be accessed it by Map.Entry name. It provides methods to get key and value.

Methods of Entry interface:

  1. public Object getKey(): is used to obtain key.
  2. public Object getValue():is used to obtain value.

HashMap class:-

HashMap maintains key and value pairs.
HashMap implements Map interface.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It maintains no order.

HashMap is similar to Hashtable with two exceptions –
 HashMap methods are unsynchornized and it allows null key and null values unlike Hashtable.
It is used for maintaining key and value mapping.
It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. Example:

import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Details {

   public static void main(String args[]) {

      /* This is how to declare HashMap */
      HashMap<Integer, String> hmap = new HashMap<Integer, String>();

      /*Adding elements to HashMap*/
      hmap.put(12, "Chaitanya");
      hmap.put(2, "Rahul");
      hmap.put(7, "Singh");
      hmap.put(49, "Ajeet");
      hmap.put(3, "Anuj");

      /* Display content using Iterator*/
      Set set = hmap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry mentry = (Map.Entry)iterator.next();
         System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
         System.out.println(mentry.getValue());
      }

      /* Get values based on key*/
      String var= hmap.get(2);
      System.out.println("Value at index 2 is: "+var);

      /* Remove values based on key*/
      hmap.remove(3);
      System.out.println("Map key and values after removal:");
      Set set2 = hmap.entrySet();
      Iterator iterator2 = set2.iterator();
      while(iterator2.hasNext()) {
          Map.Entry mentry2 = (Map.Entry)iterator2.next();
          System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
          System.out.println(mentry2.getValue());
       }

   }
}
Output:
key is: 49 & Value is: Ajeet
key is: 2 & Value is: Rahul
key is: 3 & Value is: Anuj
key is: 7 & Value is: Singh
key is: 12 & Value is: Chaitanya
Value at index 2 is: Rahul
Map key and values after removal:
Key is: 49 & Value is: Ajeet
Key is: 2 & Value is: Rahul
Key is: 7 & Value is: Singh
Key is: 12 & Value is: Chaitanya




 

No comments:

Post a Comment