What is Hashtable in Java with Example

Hashtable class in Java is a concrete implementation of abstract Dictionary class. It is a data structure similar to Java HashMap that can store a collection of elements (objects) in the form of key-value pairs (entries).

Key objects must implement hashCode() and equals() methods to store and retrieve values from the Hashtable. In other words, Hashtable can only store key objects that override hashCode() and equals() methods defined by the Object class.

The main difference between Hashtable and HashMap is the way they work with thread access.

Hashtable class is a synchronized class that means it is thread-safe. Multiple threads cannot access the same instance of the Hashtable class concurrently (at the same time).

HashMap class is not synchronized which means it is not thread-safe. Multiple threads can access the same instance of HashMap class simultaneously. Therefore, it is safe to use only when one thread uses an object.

Java Hashtable was added in JDK 1.0 version and present in java.util.Hashtable package. Prior to JDK 1.2 version, Hashtable was used for mapping keys with values.

Later on, Java 1.2 version modified Hashtable so that it implements Map interface. Thus, Hashtable has been integrated with Java collections framework. But it is not quite consistent with the Java Collections Framework, it is now regarded as a “legacy class.”

Hierarchy of Java Hashtable


Hashtable class extends Dictionary class and implements Map, Cloneable, and Serializable interfaces. The hierarchy diagram of Hashtable in Java is shown in the below diagram.

Java Hashtable hierarchy diagram

Hashtable class declaration


Hashtable in Java is a generic class made by JDK 1.5 that can be declared as follows:

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

Here, Hashtable accepts two parameters K and V where K represents the type of keys and V defines the type of values.

Features of Hashtable


There are several features of Hashtable in Java that must keep in mind to use it.

1. The underlying data structure for Java Hashtable is a hash table only.

2. Insertion order is not preserved. That means it does not maintain insertion order.

3. Duplicate keys are not allowed but values can be duplicated.

4. Heterogeneous objects are allowed for both keys and values.

5. Null is not allowed for both key and values. If we attempt to store null key or value, we will get a RuntimeException named NullPointerException.

6. Java Hashtable implements Serializable and Cloneable interfaces but not random access.

7. Every method present in Hashtable is synchronized. Hence, Hashtable object is thread-safe.

8. Hashtable is the best choice if our frequent operation is a retrieval (search) operation.

9. Since Hashtable is synchronized, its operations are slower as compared to HashMap in java.

Constructors of Hashtable class in Java


Hashtable class defines the following constructors that are as follows:

1. Hashtable(): This form of constructor constructs a new, empty hashtable object with a default initial capacity as 11 and load factor as 0.75.
To store a string as key and an integer object as its value, we can create a Hashtable object as:

Hashtable<String,Integer> ht = new Hashtable<>();

The default initial capacity for this hashtable object will be taken as 11 and load factor 0.75.

2. Hashtable(int initialCapacity): This constructor constructs a new, empty hashtable with the specified initial capacity and default load factor as 0.75. If the initial capacity is less than zero, it will throw an exception named IllegalArgumentException.

3. Hashtable(int initialCapacity, float loadFactor): This constructor constructs a new, empty hashtable with the specified initial capacity and the specified load factor.

4. Hashtable(Map m): This form of constructor constructs a new hashtable with the same mappings as the given Map. If the specified map is null, it will throw NullPointerException.

Hashtable Methods in Java


Java Hashtable class defines the following legacy methods:

1. void clear(): It is used to clear all key-value pairs from the Hashtable.

2. Object clone(): This method is used to create a shallow copy of this hashtable.

3. V put(K key, V value): This method is used to map key-value pairs into the Hashtable.

4. void putAll(Map t): This method copies all of the key-value pairs (mappings) from the specified map into the Hashtable.

5. boolean isEmpty(): It returns true if there are no entries in the Hashtable.

6. int size(): This method is used to retrieve the number of key-value pairs in the Hashtable.

7. V remove(Object key): This method is used to remove the key (and its associated value) from the hashtable.

8. boolean remove(Object key, Object value): This method removes the entry for the specified key only if it is currently mapped to the specified value.

9. V replace(K key, V value): This method is used to replace the entry for the specified key only if it is currently mapped to some value.

10. boolean replace(K key, V oldValue, V newValue): This method replaces the key-value pair for the specified key only if currently mapped to the specified value.

11. boolean contains(Object value): This method checks Hashtable and returns true if hash table contains the specified value.

12. boolean containsKey(Object key): This method searches hash table and returns true if the specified key object in the hashtable.

13. boolean containsValue(Object value): This method searches hash table and returns true if this hashtable maps one or more keys to this value.

14. Enumeration<V> elements(): This method returns an enumeration of the values in this hashtable.

15. Enumeration<K> keys(): This method returns an enumeration of the keys in this hashtable.

16. Set<Map.Entry<K,V>> entrySet(): This method returns a set or collection view of the mappings contained in this map.

17. Set<K> keySet(): It returns a set view of the keys contained in this map.

18. Collection<V> values(): It returns a collection view of the values contained in this map.

19. V get(Object key): It returns the value associated with its specified key. It returns null if the key does not have a value associated with it.

20. boolean equals(Object o): It is used to compare the specified Object for equality, as per the definition in the Map interface.

21. int hashCode(): This method returns the value of hash code as per the definition in the Map interface.

22. String toString(): This method is used to convert Hashtable objects into a string in the form of a set of entries, enclosed in braces and separated by the ASCII characters “, ” (comma and space) and returns it.

Java Hashtable Example Programs


Let’s take various example programs for performing operations based on methods of hash table in java.

1. Let’s create a program where we will perform various operations such as adding, removing, checking hash table is empty or not before adding elements, and size.

In this example, we will create a constructor with default initial capacity of 11 and load factor 0.75. Look at the source code to understand better.

Program source code 1:

import java.util.Hashtable;

public class HashtableEx {	
public static void main(String[] args) 
{
// Create a Hashtable object.	
  Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
  
// Checking hashtable is empty or not.
   boolean isEmpty = ht.isEmpty();
   System.out.println("Is hash table empty: " +isEmpty);

// Adding entries using put() method in hash table.
  ht.put(1, "One"); // ht.size() is 1.
  ht.put(2, "Two"); // ht.size() is 2.
  ht.put(3, "Three"); // ht.size() is 3.
  ht.put(4, "Four"); // ht.size() is 4.
  ht.put(5, "Five"); // ht.size() is 5.
  ht.put(6, "Six"); // ht.size() is 6.
 
System.out.println("Displaying entries in hash table: " +ht);
int size = ht.size();
System.out.println("Size of hash table: " +size);

// Removing last entry.
  String removeE = ht.remove(6);
  System.out.println("Removed entry: " +removeE);
  System.out.println("Updated entries in hash table: " +ht);
  
// Getting the value of 4.
   String getValue = ht.get(4);
   System.out.println("Getting the value of 4: " +getValue);
   System.out.println("Getting the value of 2: " +ht.get(2));
  }
}
Output:
      Is hash table empty: true
      Displaying entries in hash table: {6=Six, 5=Five, 4=Four, 3=Three, 2=Two, 1=One}
      Size of hash table: 6
      Removed entry: Six
      Updated entries in hash table: {5=Five, 4=Four, 3=Three, 2=Two, 1=One}
      Getting the value of 4: Four
      Getting the value of 2: Two

As you can observe in the output of program, the insertion order is not retained in the hashtable. Internally, for every entry, a separate hash code of key is generated and the entries are indexed based on the hash code of keys to make it more efficient.

2. Let’s create another program where we will perform various operations based on methods such as replace(), containsKey(), and containsValue().

Program source code 2:

import java.util.Hashtable;
public class HashtableEx2 {	
public static void main(String[] args) 
{
// Create a Hashtable object.	
  Hashtable<String, Integer> ht = new Hashtable<>();

  ht.put("John", 20); 
  ht.put("Shubh", 30); 
  ht.put("Peter", 25);
  ht.put("Deep", 15); 
  ht.put("Jonshan", 40);
 
System.out.println("Original entries of hash table: " +ht);

// Replacing an entry for specified key from hash table.
   Integer replace = ht.replace("Peter", 60);
   System.out.println("Replacing entry for specified key: " +replace);
   System.out.println("Updated entries in hash table: " +ht);
   
// Checking specified key present in hash table.
   boolean containsKey = ht.containsKey("Shubh");
   System.out.println("Is key Shubh in hash table: " +containsKey);
   
// Checking specified value present in hash table.
   boolean containsValue = ht.containsValue(40);
   System.out.println("Is value 40 in hash table: " +containsValue);
  }
}
Output:
      Original entries of hash table: {John=20, Jonshan=40, Shubh=30, Deep=15, Peter=25}
      Replacing entry for specified key: 25
      Updated entries in hash table: {John=20, Jonshan=40, Shubh=30, Deep=15, Peter=60}
      Is key Shubh in hash table: true
      Is value 40 in hash table: true

3. Let’s take an example program where we will iterate keys, values, and entries of hash table using iterator(), keySet(), values(), and entrySet().

Program source code 3:

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;

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

  ht.put("John", 20); 
  ht.put("Shubh", 30); 
  ht.put("Peter", 25);
  ht.put("Deep", 15); 
  ht.put("Jonshan", 40);
 
System.out.println("Original entries of hash table: " +ht);

// Iterating elements of hash table using iterator() method.
   System.out.println("Iterating keys of hash table:"); 
   Iterator<String> itr = ht.keySet().iterator(); 
   while(itr.hasNext())  
   {  
    System.out.println(itr.next());  
   } 
 System.out.println("\n");

System.out.println("Iterating values of hash table:"); 
Iterator<Integer> itrValue = ht.values().iterator(); 
while(itrValue.hasNext())  
{  
 System.out.println(itrValue.next());  
} 
System.out.println("\n");
System.out.println("Iterating entries of hash table:");
Iterator<Entry<String, Integer>> itrEntry = ht.entrySet().iterator(); 
while(itrEntry.hasNext())  
{  
 System.out.println(itrEntry.next());  
} 
 }
}
Output:
      Original entries of hash table: {John=20, Jonshan=40, Shubh=30, Deep=15, Peter=25}
      Iterating keys of hash table:
      John
      Jonshan
      Shubh
      Deep
      Peter

      Iterating values of hash table:
      20
      40
      30
      15
      25

      Iterating entries of hash table
      John=20
      Jonshan=40
      Shubh=30
      Deep=15
      Peter=25

Hope that this tutorial has covered basic points of Hashtable in Java with example programs. I hope that you will have understood how to iterate Hashtable.
Thanks for reading!!!