What Is A Java HashTable: HashTable Implementation & Example

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 9, 2024

This Tutorial Explains What is a Java HashTable, Constructors, and Methods of Hashtable Class, Implementation & Hashtable vs Hashmap:

What Is A HashTable?

A Hashtable in Java is an array of elements that are lists. Each of these lists is termed a bucket.

It maps the keys to values. In Java, the hash table is implemented by the ‘HashTable’ class. This class implements the map interface and inherits the dictionary class.

=> Check Out The Perfect Java Training Guide Here.

Hash Table in Java

Some of the unique characteristics of Hashtable in Java are as follows:

  1. It is an array that contains lists or buckets as its elements.
  2. It has unique elements.
  3. There is no null key or null value in the Hashtable.
  4. It is similar to Hashmap but is synchronized.

HashTable Class In Java

In Java, this class is a member of java.util package. Thus we have to include one of the following statements in our program to include HashTable class functionality.

import java.util.*;

OR

import java.util.HashTable;

A general class declaration for java.util.HashTable class is given below:

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

Here,

  • K => type of keys of the HashTable
  • V=> type of values mapped

The HashTable class API consists of constructors that are used to construct the class objects and the various operations or methods that are a part of the class which brings about smooth functioning of the HashTable class.

Constructors Of HashTable Class

Constructor PrototypeDescription
Hashtable ()Default constructor: creates a HashTable class object with initial default capacity and load factor.
Hashtable (int capacity) Creates a hash table with the specified initial capacity.
Hashtable (int capacity, float loadFactor)Creates a hash table object with the initial capacity =capacity and load factor = loadFactor.
Hashtable (Map< ? extends K,? extends V > t)Creates a new hashTable from the given map specified as the argument.

Methods Of HashTable Class

MethodMethod PrototypeDescription
clearvoid clear () Clears the HashTable by resetting the values.
cloneObject clone () Makes a shallow copy of the HashTable object and returns it.
computeV compute ( K key, BiFunction< ? super K,? super V,? extends V > remappingFunction)Computes mapping between the given key and the value using the remapping function.
computeIfAbsentV computeIfAbsent( K key, Function< ? super K,? extends V > mappingFunction) Computes mapping between the given key and the value using the remapping function if the specified key is not already associated with the given value.
computeIfPresentV computeIfPresent(K key, BiFunction< ? super K,? super V,? extends V > remappingFunction) If the given key is present, the remapping function is used to compute a new mapping between the given key and the value.
elementsEnumeration elements () It returns an enumeration of the values in the hash table.
SetSet< Map.Entry< K,V >> entrySet() It returns a set view of the mappings contained in the map.
equalsboolean equals (Object o) Compares the given object with the HashTable.
forEachvoid forEach (BiConsumer< ? super K,? super V > action) The given action is performed for each of the HashTable elements until all elements are exhausted.
getOrDefaultV 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.
hashCodeint hashCode () Returns the hash code of the HashTable.
keysEnumeration< K > keys () Returns keys in the HashTable as an enumeration.
keySetSet< K > keySet ()Returns the keyset (keys as a set) for the HashTable.
mergeV merge (K key, V value, BiFunction< ? super V,? super V,? extends V > remappingFunction) Maps the given key with the non-null value using remapping function if the key is not already present or null.
putV put( K key, V value) Inserts a new key-value pair in the HashTable.
putAllvoid putAll( Map< ? extends K,? extends V > t))Puts or copies the key-value pairs of the given map into the HashTable.
putIfAbsentV putIfAbsent( K key, V value) Associates the given key with the null value if the key is not already present or associated with null.
removeboolean remove ( Object key, Object value)Deletes the given key-value pair from the HashTable.
replaceV replace ( K key, V value)It replaces the value of the given key with the specified value.
replaceboolean replace ( K key, V oldValue, V newValue) Replaces the old value of the given key with the new value.
replaceAllvoid replaceAll(BiFunction function) All the entries in the HashTable are replaced by the value that is obtained from evaluating the given function.
toStringString toString () Converts the HashTable object into its string representation.
valuesCollection values () Returns the values in the HashTable as a collection.
containsboolean contains (Object value) Checks if the given value is present in the HashTable. Returns true if present else returns false.
contains valueboolean containsValue (Object value)Checks if there is a value equal to the given value in the HashTable and returns true.
containsKeyboolean containsKey (Object key) Checks if there is any key equal to the given key in the HashTable and returns true if yes.
isEmptyboolean isEmpty () Checks if the given HashTable is empty and returns true if yes.
rehashprotected void rehash () It is used to increase the size of the hash table and rehashes all of its keys.
getV get (Object key) Retrieves the value for the given key.
removeV remove (Object key) Deletes the given key and value and returns this value.
sizeint size () Returns the size or number of elements present in the HashTable.

Implementation Of HashTable

Given below is the implementation of the class in Java. Here we have demonstrated all the important methods provided by the class.

import java.util.*;  
class Main{  
 public static void main(String args[]){  
    //create a Hashtable and initiliaze it
    Hashtable&amp;lt;Integer,String&amp;gt; hash_tab=new Hashtable&amp;lt;Integer,String&amp;gt;();  
    hash_tab.put(100,"Red");  
    hash_tab.put(101,"Green");  
    hash_tab.put(104,"Blue");  
    hash_tab.put(102,"Orange");  
    hash_tab.put(103,"Brown");
    
    //obtain entrySet for the Hashtable and print the elments
    System.out.println("The contents of Hashtable:");
    for(Map.Entry m:hash_tab.entrySet()){  
        System.out.println(m.getKey()+" : "+m.getValue());  
    }  
    //getOrDefault operation =&amp;gt; get the value at given key or output default message
    System.out.println("Hashtable Value at 101: " + hash_tab.getOrDefault(101, "Value Not Found"));  
    System.out.println("Hashtable Value at 105: " +hash_tab.getOrDefault(105, "Value Not Found"));  
    //remove operation =&amp;gt; delete value at given key    
    hash_tab.remove(102);  
    System.out.println("After remove(102), the Hash Table: "+ hash_tab); 
    //putIfAbsent operation=&amp;gt;update the key-value pair in table if absent
    hash_tab.putIfAbsent(102,"Orange");  
    System.out.println("Updated Hash Table: "+hash_tab);  
 }  
}  

Output:

The contents of Hashtable:
104 : Blue
103 : Brown
102 : Orange
101 : Green
100 : Red
Hashtable Value at 101: Green
Hashtable Value at 105: Value Not Found
After remove(102), the Hash Table: {104=Blue, 103=Brown, 101=Green, 100=Red}
Updated Hash Table: {104=Blue, 103=Brown, 102=Orange, 101=Green, 100=Red}

output - Java Implementation

HashTable Java Example

In this program, we define a hashtable with the keys as the account holder names with their respective account balances as values. First, we retrieve the keys from the HashTable as an enumeration. Then using this enumeration, we print the key-value pairs from the HashTable.

Later, we update the account balance of one of the holders and print the updated amount.

The program given below shows this implementation.

import java.util.*;
public class Main {

   public static void main(String args[]) {
      // Create a Hashtable of account balance
      Hashtable acc_balance = new Hashtable();
      Enumeration person_names;
      String name_str;
      double balance;
      //initialize the Hashtable
      acc_balance.put("Lily", new Double(4367.34));
      acc_balance.put("Ben", new Double(95.43));
      acc_balance.put("Lacy", new Double(1200.00));
      acc_balance.put("Dillon", new Double(499.22));
      acc_balance.put("James", new Double(78.48));

      // retrieve the keys of the Hashtable
      person_names = acc_balance.keys();
      
      System.out.println("The account balance Hashtable:");
      System.out.println("\t KEY     VALUE\t");
      //print the contents of Hashtable
      while(person_names.hasMoreElements()) {
         name_str = (String) person_names.nextElement();
         System.out.println("\t" + name_str + "\t" + acc_balance.get(name_str));
      }        
      System.out.println();
      
      // Update Ben's Account by adding 1000 to it.
      balance = ((Double)acc_balance.get("Ben")).doubleValue();
      acc_balance.put("Ben", new Double(balance + 1000));
      //print the contents of updated account
      System.out.println("Ben's new Account balance: " + acc_balance.get("Ben"));
   }
}

Output:

The account balance Hashtable:
KEY VALUE
James 78.48
Ben 95.43
Dillon 499.22
Lily 4367.34
Lacy 1200.0

Ben’s new Account balance: 1095.43

output - Java Hashtable example

Hashtable Vs Hashmap

HashTableHashMap
Inherits dictionary class.Inherits AbstractMap class.
Is a legacy class.HashMap class introduced in JDK 1.2
Synchronized and thread-safe.Non-synchronized and non-thread safe.
It is synchronized internally and cannot be undone.It can be synchronized using Collections.synchronizedMap method.
No null key/value allowed.Allows null key and multiple null values.
Can be traversed using Enumerator and Iterator.Can be traversed only using Iterator.
HashTable is slow to execute.HashMap is faster.

Frequently Asked Questions

Q #1) What is Hashtable in Java? 

Answer: It is a legacy class that inherits the “dictionary” class and stores key-value pairs.

Q #2) Why Hashtable is used?

Answer: It is used to store key-value pairs. So when we need to store the key-value pairs in the tabular format we go for HashTable. Secondly, it can store multiple values for the same key using buckets. Data retrieval is efficient in HashTables.

Q #3) How do you create a Hashtable in Java?

Answer: You can create it by instantiating an object of java.util.HashTable class.

HashTable<String,String> hashTable = new HashTable<String,String>();

The above statement creates a HashTable named ‘hashTable’ with Keys and values of type String.

Q #4) Is Hashtable thread-safe?

Answer: Yes, it is thread-safe. In case thread safeness is not required, then we can opt for HashMap.

Q #5) How does Hashtable work internally in Java with an example?

Answer: Internally it stores key-value pairs in a structure called buckets. The position of the bucket is determined by the key’s hashCode. The hash function gets the bucket location using the Key’s hashCode.

Conclusion

HashTable consists of data stored in the form of key-value pairs. The keys or values cannot be null. In Java, it is implemented using the HashTable class.

We have seen the constructors and methods provided by the HashTable class along with the implementation of HashTable in the Java language.

In our upcoming tutorial, we will discuss the HashMap collection.

=> Visit Here For The Exclusive Java Training Tutorial Series.

Was this helpful?

Thanks for your feedback!

Leave a Comment