HashTable in Java

  • The HashTable class extends Dictionary and implements Map interface.
  • The Hashtable internally contains buckets in which it stores the key or value pairs.
  • The HashTable can only store objects that override the hashCode() and equals() methods that are defined by Object.
  • The HashTable value can get by Enumeration interface.
  • The HashTable do not permit null values as key and value.
  • The HashTable is synchronized.
  • The HashTable is less efficient compared to HashMap.
  • The two most important HashTables methods are:
get(Object Key) -  returns the value associated with specified key in this hash table, or null if there is no value for this key.

put(Object Ket, Object Value) - associates the specified value with the specified key in hash table.

The following table demonstrates the constructors of HashTable and their meanings.

Constructor
Meaning
HashTable()
Constructs a new empty map object.
HashTable(Map m)
Constructs a new map with the given map.
HashTable(int Capacity)
Constructs a new map with the given capacity.
HashTable(int Capacity, float loadfactor)
Constructs a new map with the given capacity and the given load factor.

The following program shows a simple use of HashTable.

Example:

/**
From SimpleHashTable.java
*/

import java.util.Hashtable;

/**
 *
 * @author JavaHotSpot
 */

public class SimpleHashTable
{
 public static void main(String args[])
  {
      Hashtable<String,Float> htable = new Hashtable<String,Float>();
      htable.put("Apple", new Float(88.91));
      htable.put("Grape", new Float(78.45));
      htable.put("Banana", new Float(92.61));
      htable.put("Mango", new Float(95.11));
      htable.put("Orange", new Float(82.54));
      htable.put("Pinapple", new Float(73.41));
      System.out.println("The HashTable elements are"+"\n"+htable);
  }
}

Output
The HashTable elements are
{Mango=95.11, Orange=82.54, Pinapple=73.41, Grape=78.45, Apple=88.91, Banana=92.61}

The following program shows use of HashTable with Enumeration Interface.

Example:

/**
From HashTablewithEnumeration.java
*/

import java.util.Enumeration;
import java.util.Hashtable;

/**
 *
 * @author JavaHotSpot
 */

public class HashTablewithEnumeration
{
 public static void main(String args[])
  {
      String ss;
      Hashtable<String,Float> htable = new Hashtable<String,Float>();
      htable.put("Apple", new Float(88.91));
      htable.put("Grape", new Float(78.45));
      htable.put("Banana", new Float(92.61));
      htable.put("Mango", new Float(95.11));
      htable.put("Orange", new Float(82.54));
      htable.put("Pinapple", new Float(73.41));
      System.out.println("The HashTable elements are");
      Enumeration em = htable.keys();
      while(em.hasMoreElements())
      {
         ss = (String)em.nextElement();
         System.out.println(ss +"="+htable.get(ss));
      }
  }
}

Output
The HashTable elements are
Mango=95.11
Orange=82.54
Pinapple=73.41
Grape=78.45
Apple=88.91