Hashtable Class in Java Framework

Hashtable Class

The Hashtable class is synchronized i.e. it is thread-safe. It does not contain any duplicate values. It cannot contain any null key or null value. It is similar to HashMap. It stores the key/values pair in hash table.

Example: Program to implement methods available in Hashtable class


import java.util.*;
public class HashtableDemo
{
      public static void main(String args[])
      {
            //creates Hashtable
            Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
            System.out.println("Initial size of Hashtable: "+ht.size());
            System.out.println("Hashtable in empty: "+ht.isEmpty());

             //inserting the element
             ht.put(3, "Java");
             ht.put(5, "Oracle");
             ht.put(new Integer(1),"HTML");
             ht.put(new Integer(7), "SQL Server");

              //ht.put(null, null); NullPointerException
              //Retrieve the data
              for(Map.Entry m:ht.entrySet())
              {  
                     System.out.println(m.getKey()+": "+m.getValue());
              }  
              System.out.println("Size of Hashtable after adding: "+ht.size());
              System.out.println("Hashtable in empty: "+ht.isEmpty());
      }
}


Output:
Initial size of Hashtable: 0
Hashtable in empty: true
7: SQL Server
5: Oracle
3: Java
1: HTML
Size of Hashtable after adding: 4
Hashtable in empty: false