Signup/Sign In

Java Collection Framework Hashtable

Java Hashtable is an implementation of hash table which stores elements in key-value pair. It does not allow null key and null values. It is synchronized version of HashMap.

It extends Dictionary class and implements Map interface. Declaration of this class is given below.

Hashtable Declaration

public class Hashtable<K,V>extends Dictionary<K,V>implements Map<K,V>, Cloneable, Serializable

Important Points

  • It contains values based on the key.
  • It contains unique elements.
  • It doesn't allow null key or value.
  • It is synchronized.
  • The initial default capacity of Hashtable is 11.

In this tutorial, we will learn to create a Hashtable, add new elements to it, traverse its elements etc.

Hashtable Constructors

Constructor Description
Hashtable() It creates an empty hashtable having the initial default capacity and load factor.
Hashtable(int capacity) It accepts an integer parameter and creates a hash table that contains a specified initial capacity.
Hashtable(int capacity, float loadFactor) It is used to create a hash table having the specified initial capacity and loadFactor.
Hashtable(Map<? extends K,? extends V> t) It creates a new hash table with the same mappings as the given Map.

Example: Creating Hashtable

Lets take an example to create hashtable that takes elements of string and integer type pair. Initially it is empty so if we print it, it shows empty braces. We will learn to add elements in next example.

  
import java.util.*;

class Demo
{
  public static void main(String args[])
  {
    // Creating Hashtable
    Hashtable<String,Integer> hashtable = new Hashtable<String,Integer>();

    // Displaying Hashtable
    System.out.println(hashtable);
    
  }
}
  

{}

Hashtable Methods

Method Description
void clear() It empty the hash table.
Object clone() It returns a shallow copy of the Hashtable.
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) It computes a mapping for the specified key and its current mapped value.
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) It computes its value using the given mapping function.
Enumeration elements() It returns an enumeration of the values in the hash table.
Set<Map.Entry<K,V>> entrySet() It returns a set view of the mappings contained in the map.
boolean equals(Object o) It compares the specified Object with the Map.
void forEach(BiConsumer<? super K,? super V> action) It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
int hashCode() It returns the hash code value for the Map
Enumeration<K> keys() It returns an enumeration of the keys in the hashtable.
Set<K> keySet() It returns a Set view of the keys contained in the map.
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
V put(K key, V value) It inserts the specified value with the specified key in the hash table.
void putAll(Map<? extends K,? extends V> t)) It is used to copy all the key-value pair from map to hashtable.
V putIfAbsent(K key, V value) If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys from the hashtable.
V replace(K key, V value) It replaces the specified value for a specified key.
String toString() It returns a string representation of the Hashtable object.
Collection values() It returns a collection view of the values contained in the map.
boolean contains(Object value) This method returns true if some value equal to the value exists within the hash table, else return false.
boolean containsValue(Object value) This method returns true if some value equal to the value exists within the hash table, else return false.
boolean containsKey(Object key) This method return true if some key equal to the key exists within the hash table, else return false.
boolean isEmpty() This method returns true if the hash table is empty; returns false if it contains at least one key.
protected void rehash() It is used to increase the size of the hash table and rehashes all of its keys.
V get(Object key) This method returns the object that contains the value associated with the key.
V remove(Object key) It is used to remove the key and its value. This method returns the value associated with the key.
int size() This method returns the number of entries in the hash table.

Adding Elements to Hashtable

To insert elements into the hashtable, we are using put() method that adds new elements. It takes two argument: first is key and second is value.

  
import java.util.*;

class Demo
{
  public static void main(String args[])
  {
    // Creating Hashtable
    Hashtable<String,Integer> hashtable = new Hashtable<String,Integer>();
    // Adding elements
    hashtable.put("a",100);
    hashtable.put("b",200);
    hashtable.put("c",300);
    hashtable.put("d",400);
    // Displaying Hashtable
    System.out.println(hashtable);
    
  }
}
  

{b=200, a=100, d=400, c=300}

Example: No Null Allowed

Since hashtable does not allow null key or value then forcing to insert the null will throw an error. See the below example.

  
import java.util.*;

class Demo
{
  public static void main(String args[])
  {
    // Creating Hashtable
    Hashtable<String,Integer> hashtable = new Hashtable<String,Integer>();
    // Adding elements
    hashtable.put("a",100);
    hashtable.put("b",200);
    hashtable.put("c",300);
    hashtable.put("d",400);
    hashtable.put(null, 0); // error: no null allowed
    // Displaying Hashtable
    System.out.println(hashtable);
    
  }
}
  

Exception in thread "main" java.lang.NullPointerException

Example: Search for a key or value

Hashtable provides various methods such as contains(), containsKey() etc to search for an element in the hashtable. Contains() method search for specified value while containsKey() method search for specified key.

  
import java.util.*;

class Demo
{
  public static void main(String args[])
  {
    // Creating Hashtable
    Hashtable<String,Integer> hashtable = new Hashtable<String,Integer>();
    // Adding elements
    hashtable.put("a",100);
    hashtable.put("b",200);
    hashtable.put("c",300);
    hashtable.put("d",400);
    // Displaying Hashtable
    System.out.println(hashtable);
    // Search for a value
    boolean val = hashtable.contains(400);
    System.out.println("is 400 present: "+val);
    // Search for a key
    val = hashtable.containsKey("d");
    System.out.println("is d present: "+val);   
  }
}
  

{b=200, a=100, d=400, c=300} is 400 present: true is d present: true

Example: Traverse Hashtable

We can traverse the hashtable elements using loop to access its elements and to get list of all the available elements.

  
import java.util.*;

class Demo
{
  public static void main(String args[])
  {
    // Creating Hashtable
    Hashtable<String,Integer> hashtable = new Hashtable<String,Integer>();
    // Adding elements
    hashtable.put("a",100);
    hashtable.put("b",200);
    hashtable.put("c",300);
    hashtable.put("d",400);
    // Traversing Hashtable
    for(Map.Entry<String, Integer> m : hashtable.entrySet()) {
      System.out.println(m.getKey()+" "+m.getValue());
    }   
  }
}
  

b 200 a 100 d 400 c 300