What Is A Java HashTable - HashTable Implementation & Example

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

Methods Of HashTable Class

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;amp;amp;lt;Integer,String&amp;amp;amp;gt; hash_tab=new Hashtable&amp;amp;amp;lt;Integer,String&amp;amp;amp;gt;();
    hash_tab.put(100,&amp;quot;Red&amp;quot;);
    hash_tab.put(101,&amp;quot;Green&amp;quot;);
    hash_tab.put(104,&amp;quot;Blue&amp;quot;);
    hash_tab.put(102,&amp;quot;Orange&amp;quot;);
    hash_tab.put(103,&amp;quot;Brown&amp;quot;);

    //obtain entrySet for the Hashtable and print the elments
    System.out.println(&amp;quot;The contents of Hashtable:&amp;quot;);
    for(Map.Entry m:hash_tab.entrySet()){
        System.out.println(m.getKey()+&amp;quot; : &amp;quot;+m.getValue());
    }
    //getOrDefault operation =&amp;amp;amp;gt; get the value at given key or output default message
    System.out.println(&amp;quot;Hashtable Value at 101: &amp;quot; + hash_tab.getOrDefault(101, &amp;quot;Value Not Found&amp;quot;));
    System.out.println(&amp;quot;Hashtable Value at 105: &amp;quot; +hash_tab.getOrDefault(105, &amp;quot;Value Not Found&amp;quot;));
    //remove operation =&amp;amp;amp;gt; delete value at given key
    hash_tab.remove(102);
    System.out.println(&amp;quot;After remove(102), the Hash Table: &amp;quot;+ hash_tab);
    //putIfAbsent operation=&amp;amp;amp;gt;update the key-value pair in table if absent
    hash_tab.putIfAbsent(102,&amp;quot;Orange&amp;quot;);
    System.out.println(&amp;quot;Updated Hash Table: &amp;quot;+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(&amp;quot;Lily&amp;quot;, new Double(4367.34));
      acc_balance.put(&amp;quot;Ben&amp;quot;, new Double(95.43));
      acc_balance.put(&amp;quot;Lacy&amp;quot;, new Double(1200.00));
      acc_balance.put(&amp;quot;Dillon&amp;quot;, new Double(499.22));
      acc_balance.put(&amp;quot;James&amp;quot;, new Double(78.48));

      // retrieve the keys of the Hashtable
      person_names = acc_balance.keys();

      System.out.println(&amp;quot;The account balance Hashtable:&amp;quot;);
      System.out.println(&amp;quot;\t KEY     VALUE\t&amp;quot;);
      //print the contents of Hashtable
      while(person_names.hasMoreElements()) {
         name_str = (String) person_names.nextElement();
         System.out.println(&amp;quot;\t&amp;quot; + name_str + &amp;quot;\t&amp;quot; + acc_balance.get(name_str));
      }
      System.out.println();

      // Update Ben's Account by adding 1000 to it.
      balance = ((Double)acc_balance.get(&amp;quot;Ben&amp;quot;)).doubleValue();
      acc_balance.put(&amp;quot;Ben&amp;quot;, new Double(balance + 1000));
      //print the contents of updated account
      System.out.println(&amp;quot;Ben's new Account balance: &amp;quot; + acc_balance.get(&amp;quot;Ben&amp;quot;));
   }
}

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


Frequently Asked Questions

1. What is Hashtable in Java? 

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

2. Why Hashtable is used?

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.

3. How do you create a Hashtable in Java?

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.

4. Is Hashtable thread-safe?

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

5. How does Hashtable work internally in Java with an example?

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!