Java: HashTable Class Methods and Examples

The hashtable class implements a Map interface and extends Dictionary Class to store key and values as pairs.

Hashtable is an array of the list where each list is known as a bucket of the node (key and value pair). The position of the node is identified by calling the hashcode() method on key.

Points to remember

  • Hashtable class is in java.util package.
  • Hashtable contains unique elements.
  • Hashtable doesn’t allow null key or value.
  • Hashtable is synchronized.
  • Hashtable initial default capacity is 11 whereas the load factor is 0.75.

See Also:

Hashtable class declaration

Let’s see the declaration for java.util.Hashtable class.


public class Hashtable extends Dictionary implements Map, Cloneable, Serializable  
  • K: Represent as key in Map
  • V: Represent as value with respect to K.

Constructors of java.util.Hashtable class

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 t) It creates a new hash table with the same mappings as the given Map.

Methods of java.util.Hashtable class

Method Description
void clear() Use to reset the hash table.
Object clone() It returns a shallow copy of the Hashtable.
V compute(K key, BiFunction remappingFunction) It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function mappingFunction) It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
Enumeration elements() It returns an enumeration of the values in the hash table.
Set<Map.Entry> entrySet() It returns a set view of the mappings contained in the map.
boolean equals(Object o) Use to compare the specified Object with the Map.
void forEach(BiConsumer action) It performs the 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) This method 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 keys() This method returns an enumeration of the keys in the hashtable.
Set keySet() It returns a Set view of the keys contained in the map.
V merge(K key, V value, BiFunction remappingFunction) If the specified key is not found in hashTable then 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 t)) It is used to copy all the key-value pairs from the map to the hashtable.
V putIfAbsent(K key, V value) If the specified key is not already associated with a value (or is mapped to null) in Hashtable then insert key and 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) This method replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) This method replaces the old value with the new value for a specified key.
void replaceAll(BiFunction function) This method replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
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 returns 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 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.

HashTable Example : add() key and value

import java.util.*;

public class HashTableExample1 {

	public static void main(String args[]) {
		Hashtable hm = new Hashtable();

		//add values in hash table
		hm.put(20, "Anuj");
		hm.put(22, "Ravi");
		hm.put(21, "Virendra");
		hm.put(23, "Raghav");

		//print all values from HashTable
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


21 Virendra
20 Anuj
23 Raghav
22 Ravi

HashTable Example : remove()

import java.util.Hashtable;

public class HashTableExample2 {

	public static void main(String args[]) {
		Hashtable map = new Hashtable();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		System.out.println("Before remove: " + map);
		// Remove value for key 22
		map.remove(22);
		System.out.println("After remove: " + map);
	}

}

Output :


Before remove: {21=Virendra, 20=Anuj, 23=Raghav, 22=Ravi}
After remove: {21=Virendra, 20=Anuj, 23=Raghav}

Hashtable Example : getOrDefault()

import java.util.Hashtable;

public class HashTableExample3 {

	public static void main(String args[]) {
		Hashtable map = new Hashtable();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		// Here it will retrieve values for key 21 and 25
		// if values not find out in HashTable then return default value
		System.out.println(map.getOrDefault(21, "Not Found"));
		System.out.println(map.getOrDefault(25, "Not Found"));
	}
}

Output :


Virendra
Not Found

Hashtable Example : putAbsent()

import java.util.*;
class HashtableExample4{
 public static void main(String args[]){
   Hashtable map=new Hashtable();
     map.put(20,"Anuj");
     map.put(22,"Ravi");
     map.put(21,"Virendra");
     map.put(23,"Raghav");
     System.out.println("Initial Map: "+map);
     //insert value in hashtable only when not exist
     map.putIfAbsent(24,"Gaurav");
     System.out.println("Updated Map: "+map);
     //insert value in hashtable only when not exist
     map.putIfAbsent(21,"Virendra");
     System.out.println("Updated Map: "+map);
 }
}

Output :


Initial Map: {21=Virendra, 20=Anuj, 23=Raghav, 22=Ravi}
Updated Map: {21=Virendra, 20=Anuj, 24=Gaurav, 23=Raghav, 22=Ravi}
Updated Map: {21=Virendra, 20=Anuj, 24=Gaurav, 23=Raghav, 22=Ravi}

Hashtable Example : with Objects

import java.util.*;
class Magzine{
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}    

public class HashtableExampleWithObjects {
	public static void main(String[] args) {
		// Creating map of Magzine
		Map table = new Hashtable();
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzine to map
		table.put(1, m1);
		table.put(2, m2);
		table.put(3, m3);
		// Traversing map
		for (Map.Entry entry : table.entrySet()) {
			int key = entry.getKey();
			Magzine m = entry.getValue();
			System.out.println("\nId: "+key + " Details:");
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


Id: 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

Id: 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Id: 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8