HashTable

The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

Features

  • It is similar to HashMap, but is synchronized.

  • Hashtable stores key/value pair in hash table.

  • In Hashtable we specify an object that is used as a key, and the value we want to associate to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

  • The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.

  • HashMap doesn’t provide any Enumeration, while Hashtable provides not fail-fast Enumeration.

Declaration:

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

Constructors

Hashtable()

This creates an empty hashtable with the default load factor of 0.75 and an initial capacity is 11.

Hashtable<K, V> ht = new Hashtable<K, V>();

Hashtable(int initialCapacity)

This creates a hash table that has an initial size specified by initialCapacity and the default load factor is 0.75.

Hashtable<K, V> ht = new Hashtable<K, V>(int initialCapacity);

Hashtable(int size, float fillRatio)

This version creates a hash table that has an initial size specified by size and fill ratio specified by fillRatio. fill ratio: Basically, it determines how full a hash table can be before it is resized upward and its Value lies between 0.0 to 1.0.

Hashtable<K, V> ht = new Hashtable<K, V>(int size, float fillRatio);

Hashtable(Map<? extends K,? extends V> m)

This creates a hash table that is initialized with the elements in m.

Hashtable<K, V> ht = new Hashtable<K, V>(Map m);

Operations

Adding Elements

In order to add an element to the hashtable, we can use the put() method. However, the insertion order is not retained in the hashtable. Internally, for every element, a separate hash is generated and the elements are indexed based on this hash to make it more efficient.

// adding elements to Hashtable

import java.io.*;
import java.util.*;

class AddElementsToHashtable {
    public static void main(String args[]) {
        // No need to mention the
        // Generic type twice
        Hashtable<Integer, String> ht1 = new Hashtable<>();

        // Initialization of a Hashtable
        // using Generics
        Hashtable<Integer, String> ht2
                = new Hashtable<Integer, String>();

        // Inserting the Elements
        // using put() method
        ht1.put(1, "Tit");
        ht1.put(2, "For");
        ht1.put(3, "Tat");

        ht2.put(1, "Tit");
        ht2.put(2, "For");
        ht2.put(3, "Tat");

        // Print mappings to the console
        System.out.println("Mappings of ht1 : " + ht1);
        System.out.println("Mappings of ht2 : " + ht2);
    }
}

Output

Mappings of ht1 : {3=Tat, 2=For, 1=Tit}
Mappings of ht2 : {3=Tat, 2=For, 1=Tit}

Changing Elements

After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the hashtable are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change.

// Java program to demonstrate
// updating Hashtable

import java.io.*;
import java.util.*;
class UpdatesOnHashtable {
    public static void main(String args[])
    {

        // Initialization of a Hashtable
        Hashtable<Integer, String> ht
                = new Hashtable<Integer, String>();

        // Inserting the Elements
        // using put method
        ht.put(1, "Tit");
        ht.put(2, "For");
        ht.put(3, "Tat");

        // print initial map to the console
        System.out.println("Initial Map " + ht);

        // Update the value at key 2
        ht.put(2, "Tok");

        // print the updated map
        System.out.println("Updated Map " + ht);
    }
}

Output

Initial Map {3=Tat, 2=For, 1=Tit}
Updated Map {3=Tat, 2=Tok, 1=Tit}

Removing Element

In order to remove an element from the Map, we can use the remove() method. This method takes the key value and removes the mapping for a key from this map if it is present in the map.

// Java program to demonstrate
// the removing mappings from Hashtable

import java.io.*;
import java.util.*;
class RemovingMappingsFromHashtable {

    public static void main(String args[])
    {
        // Initialization of a Hashtable
        Map<Integer, String> ht
                = new Hashtable<Integer, String>();

        // Inserting the Elements
        // using put method
        ht.put(1, "Coding");
        ht.put(2, "For");
        ht.put(3, "All");
        ht.put(4, "For");

        // Initial HashMap
        System.out.println("Initial map : " + ht);

        // Remove the map entry with key 4
        ht.remove(4);

        // Final Hashtable
        System.out.println("Updated map : " + ht);
    }
}

Output

Initial map : {4=For, 3=All, 2=For, 1=Coding}
Updated map : {3=All, 2=For, 1=Coding}

Traversal of a Hashtable

To iterate the table, we can make use of an advanced for loop. Below is the example of iterating a hashtable.

// Java program to illustrate
// traversal of Hashtable

import java.util.Hashtable;
import java.util.Map;

public class IteratingHashtable {
	public static void main(String[] args)
	{
		// Create an instance of Hashtable
		Hashtable<String, Integer> ht = new Hashtable<>();

		// Adding elements using put method
		ht.put("vishal", 10);
		ht.put("sachin", 30);
		ht.put("vaibhav", 20);
	
		// Iterating using enhanced for loop
		for (Map.Entry<String, Integer> e : ht.entrySet())
			System.out.println(e.getKey() + " "
							+ e.getValue());
	}
}

Output

vaibhav 20
vishal 10
sachin 30
core java programming hashtable collections

Subscribe For More Content