Loading

A HashTable in Java is a type of map that stores key-value pairs. It keeps keys unique, and does not allow null values.


Features

  • HashTable is an implementation class of Map Interface.
  • The hashTable class doesn't allow a null key or value.
  • It contains unique elements.
  • Java HashTable class is synchronized.
  • The initial default capacity of HashTable is 11, and it grows based on the load factor of 0.75.


Example: Adding and Retrieving Values from HashTable

package com.quipoin;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

public class HashtableDemo {
	public static void main(String[] args) {
		Hashtable<Integer, String> ht=new Hashtable<>();

		ht.put(100, "Raj");
		ht.put(102, "Keshav");
		ht.put(101, "Bharath");
		ht.put(103, "Prasad");

		System.out.println("Id\tName");
		System.out.println("---------------");
		Set<Integer> id=ht.keySet();
		Iterator<Integer> it=id.iterator();

		while(it.hasNext()) {
			Integer key=it.next();
			String value=ht.get(key);
			System.out.println(key+"\t"+value);
		}
	}
}


Output:

Id	Name
---------------
103	Prasad
102	Keshav
101	Bharath
100	Raj

Example: Removing an Entry form HashTable

package com.hashtable;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

public class HashtableDemo2 {
	public static void main(String[] args) {
		Hashtable<Integer, String> ht=new Hashtable<>();

		ht.put(100, "Amith");
		ht.put(102, "Ravi");
		ht.put(101, "Vijay");
		ht.put(103, "Rahul");

		System.out.println("Before remove:\n"+ht);

		ht.remove(102);
		System.out.println("After remove:\n"+ht);
	}
}


Output:

Before remove:
{103=Rahul, 102=Ravi, 101=Vijay, 100=Amith}
After remove:
{103=Rahul, 101=Vijay, 100=Amith}

Key Point

  • Thread Safety: HashTable works well in multi-threaded programs.
  • Performance: Slower than HashMap.
  • Unordered Elements: It does not maintain any specific order.
  • No Null Values: Prevents accidental NullPointerException errors.

Two Minute Drill

  • Use HashTable when working with multiple threads and needing a thread-safe Map.
  • If you don’t need synchronization, HashMap is a faster alternative.