Open In App

Hashtable in Java

Last Updated : 05 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.  

The java.util.Hashtable class is a class in Java that provides a key-value data structure, similar to the Map interface. It was part of the original Java Collections framework and was introduced in Java 1.0.

However, the Hashtable class has since been considered obsolete and its use is generally discouraged. This is because it was designed prior to the introduction of the Collections framework and does not implement the Map interface, which makes it difficult to use in conjunction with other parts of the framework. In addition, the Hashtable class is synchronized, which can result in slower performance compared to other implementations of the Map interface.

In general, it’s recommended to use the Map interface or one of its implementations (such as HashMap or ConcurrentHashMap) instead of the Hashtable class.

Here’s an example of how to use the Hashtable class:

Java




import java.util.Enumeration;
import java.util.Hashtable;
 
public class Main {
    public static void main(String[] args) {
        Hashtable<String, Integer> hashtable = new Hashtable<>();
 
        // Adding elements to the hashtable
        hashtable.put("A", 1);
        hashtable.put("B", 2);
        hashtable.put("C", 3);
 
        // Getting values from the hashtable
        int valueA = hashtable.get("A");
        System.out.println("Value of A: " + valueA);
 
        // Removing elements from the hashtable
        hashtable.remove("B");
 
        // Enumerating the elements of the hashtable
        Enumeration<String> keys = hashtable.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            System.out.println("Key: " + key + ", Value: " + hashtable.get(key));
        }
    }
}


Output

Value of A: 1
Key: A, Value: 1
Key: C, Value: 3

In conclusion, while the Hashtable class still exists in Java and can still be used, it’s generally recommended to use the Map interface or one of its implementations instead.

Features of Hashtable

  • It is similar to HashMap, but is synchronized.
  • Hashtable stores key/value pair in hash table.
  • In Hashtable we specify an object that is used as a key, and the value we want to associate to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.
  • The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
  • HashMap doesn’t provide any Enumeration, while Hashtable provides not fail-fast Enumeration.

Declaration:

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

Type Parameters:

  • K – the type of keys maintained by this map
  • V – the type of mapped values

The Hierarchy of Hashtable

Hierarchy of Hashtable

 

Hashtable implements Serializable, Cloneable, Map<K,V> interfaces and extends Dictionary<K,V>. The direct subclasses are Properties, UIDefaults.
 

Constructors:

In order to create a Hashtable, we need to import it from java.util.Hashtable. There are various ways in which we can create a Hashtable.

1. Hashtable(): This creates an empty hashtable with the default load factor of 0.75 and an initial capacity is 11. 

Hashtable<K, V> ht = new Hashtable<K, V>();

Java




// Java program to demonstrate
// adding elements to Hashtable
 
import java.io.*;
import java.util.*;
 
class AddElementsToHashtable {
    public static void main(String args[])
    {
        // No need to mention the
        // Generic type twice
        Hashtable<Integer, String> ht1 = new Hashtable<>();
 
        // Initialization of a Hashtable
        // using Generics
        Hashtable<Integer, String> ht2
            = new Hashtable<Integer, String>();
 
        // Inserting the Elements
        // using put() method
        ht1.put(1, "one");
        ht1.put(2, "two");
        ht1.put(3, "three");
 
        ht2.put(4, "four");
        ht2.put(5, "five");
        ht2.put(6, "six");
 
        // Print mappings to the console
        System.out.println("Mappings of ht1 : " + ht1);
        System.out.println("Mappings of ht2 : " + ht2);
    }
}


Output

Mappings of ht1 : {3=three, 2=two, 1=one}
Mappings of ht2 : {6=six, 5=five, 4=four}

2. Hashtable(int initialCapacity): This creates a hash table that has an initial size specified by initialCapacity and the default load factor is 0.75.

Hashtable<K, V> ht = new Hashtable<K, V>(int initialCapacity);

Java




// Java program to demonstrate
// adding elements to Hashtable
 
import java.io.*;
import java.util.*;
 
class AddElementsToHashtable {
    public static void main(String args[])
    {
        // No need to mention the
        // Generic type twice
        Hashtable<Integer, String> ht1 = new Hashtable<>(4);
 
        // Initialization of a Hashtable
        // using Generics
        Hashtable<Integer, String> ht2
            = new Hashtable<Integer, String>(2);
 
        // Inserting the Elements
        // using put() method
        ht1.put(1, "one");
        ht1.put(2, "two");
        ht1.put(3, "three");
 
        ht2.put(4, "four");
        ht2.put(5, "five");
        ht2.put(6, "six");
 
        // Print mappings to the console
        System.out.println("Mappings of ht1 : " + ht1);
        System.out.println("Mappings of ht2 : " + ht2);
    }
}


Output

Mappings of ht1 : {3=three, 2=two, 1=one}
Mappings of ht2 : {4=four, 6=six, 5=five}

3. Hashtable(int size, float fillRatio): This version creates a hash table that has an initial size specified by size and fill ratio specified by fillRatio. fill ratio: Basically, it determines how full a hash table can be before it is resized upward and its Value lies between 0.0 to 1.0.

Hashtable<K, V> ht = new Hashtable<K, V>(int size, float fillRatio);

Java




// Java program to demonstrate
// adding elements to Hashtable
 
import java.io.*;
import java.util.*;
 
class AddElementsToHashtable {
    public static void main(String args[])
    {
        // No need to mention the
        // Generic type twice
        Hashtable<Integer, String> ht1
            = new Hashtable<>(4, 0.75f);
 
        // Initialization of a Hashtable
        // using Generics
        Hashtable<Integer, String> ht2
            = new Hashtable<Integer, String>(3, 0.5f);
 
        // Inserting the Elements
        // using put() method
        ht1.put(1, "one");
        ht1.put(2, "two");
        ht1.put(3, "three");
 
        ht2.put(4, "four");
        ht2.put(5, "five");
        ht2.put(6, "six");
 
        // Print mappings to the console
        System.out.println("Mappings of ht1 : " + ht1);
        System.out.println("Mappings of ht2 : " + ht2);
    }
}


Output

Mappings of ht1 : {3=three, 2=two, 1=one}
Mappings of ht2 : {6=six, 5=five, 4=four}

4. Hashtable(Map<? extends K,? extends V> m): This creates a hash table that is initialized with the elements in m.

Hashtable<K, V> ht = new Hashtable<K, V>(Map m);

Java




// Java program to demonstrate
// adding elements to Hashtable
 
import java.io.*;
import java.util.*;
 
class AddElementsToHashtable {
    public static void main(String args[])
    {
        // No need to mention the
        // Generic type twice
        Map<Integer, String> hm = new HashMap<>();
 
        // Inserting the Elements
        // using put() method
        hm.put(1, "one");
        hm.put(2, "two");
        hm.put(3, "three");
 
        // Initialization of a Hashtable
        // using Generics
        Hashtable<Integer, String> ht2
            = new Hashtable<Integer, String>(hm);
 
        // Print mappings to the console
 
        System.out.println("Mappings of ht2 : " + ht2);
    }
}


Output

Mappings of ht2 : {3=three, 2=two, 1=one}

Example:

Java




// Java program to illustrate
// Java.util.Hashtable
 
import java.util.*;
 
public class GFG {
    public static void main(String[] args)
    {
        // Create an empty Hashtable
        Hashtable<String, Integer> ht = new Hashtable<>();
 
        // Add elements to the hashtable
        ht.put("vishal", 10);
        ht.put("sachin", 30);
        ht.put("vaibhav", 20);
 
        // Print size and content
        System.out.println("Size of map is:- " + ht.size());
        System.out.println(ht);
 
        // Check if a key is present and if
        // present, print value
        if (ht.containsKey("vishal")) {
            Integer a = ht.get("vishal");
            System.out.println("value for key"
                               + " \"vishal\" is:- " + a);
        }
    }
}


Output

Size of map is:- 3
{vaibhav=20, vishal=10, sachin=30}
value for key "vishal" is:- 10

Performing Various Operations on Hashtable                  

1. Adding Elements: In order to add an element to the hashtable, we can use the put() method. However, the insertion order is not retained in the hashtable. Internally, for every element, a separate hash is generated and the elements are indexed based on this hash to make it more efficient.                      

Java




// Java program to demonstrate
// adding elements to Hashtable
 
import java.io.*;
import java.util.*;
 
class AddElementsToHashtable {
    public static void main(String args[])
    {
        // No need to mention the
        // Generic type twice
        Hashtable<Integer, String> ht1 = new Hashtable<>();
 
        // Initialization of a Hashtable
        // using Generics
        Hashtable<Integer, String> ht2
            = new Hashtable<Integer, String>();
 
        // Inserting the Elements
          // using put() method
        ht1.put(1, "Geeks");
        ht1.put(2, "For");
        ht1.put(3, "Geeks");
 
        ht2.put(1, "Geeks");
        ht2.put(2, "For");
        ht2.put(3, "Geeks");
         
          // Print mappings to the console
        System.out.println("Mappings of ht1 : " + ht1);
        System.out.println("Mappings of ht2 : " + ht2);
    }
}


Output

Mappings of ht1 : {3=Geeks, 2=For, 1=Geeks}
Mappings of ht2 : {3=Geeks, 2=For, 1=Geeks}

2. Changing Elements: After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the hashtable are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change.

Java




// Java program to demonstrate
// updating Hashtable
 
import java.io.*;
import java.util.*;
class UpdatesOnHashtable {
    public static void main(String args[])
    {
 
        // Initialization of a Hashtable
        Hashtable<Integer, String> ht
            = new Hashtable<Integer, String>();
 
        // Inserting the Elements
          // using put method
        ht.put(1, "Geeks");
        ht.put(2, "Geeks");
        ht.put(3, "Geeks");
         
          // print initial map to the console
        System.out.println("Initial Map " + ht);
         
          // Update the value at key 2
        ht.put(2, "For");
         
          // print the updated map
        System.out.println("Updated Map " + ht);
    }
}


Output

Initial Map {3=Geeks, 2=Geeks, 1=Geeks}
Updated Map {3=Geeks, 2=For, 1=Geeks}

3. Removing Element: In order to remove an element from the Map, we can use the remove() method. This method takes the key value and removes the mapping for a key from this map if it is present in the map.

Java




// Java program to demonstrate
// the removing mappings from Hashtable
 
import java.io.*;
import java.util.*;
class RemovingMappingsFromHashtable {
 
    public static void main(String args[])
    {
        // Initialization of a Hashtable
        Map<Integer, String> ht
            = new Hashtable<Integer, String>();
 
        // Inserting the Elements
          // using put method
        ht.put(1, "Geeks");
        ht.put(2, "For");
        ht.put(3, "Geeks");
        ht.put(4, "For");
 
        // Initial HashMap
        System.out.println("Initial map : " + ht);
 
          // Remove the map entry with key 4
        ht.remove(4);
 
        // Final Hashtable
        System.out.println("Updated map : " + ht);
    }
}


Output

Initial map : {4=For, 3=Geeks, 2=For, 1=Geeks}
Updated map : {3=Geeks, 2=For, 1=Geeks}

4. Traversal of a Hashtable: To iterate the table, we can make use of an advanced for loop. Below is the example of iterating a hashtable.

Java




// Java program to illustrate
// traversal of Hashtable
 
import java.util.Hashtable;
import java.util.Map;
 
public class IteratingHashtable {
    public static void main(String[] args)
    {
          // Create an instance of Hashtable
        Hashtable<String, Integer> ht = new Hashtable<>();
 
          // Adding elements using put method
        ht.put("vishal", 10);
        ht.put("sachin", 30);
        ht.put("vaibhav", 20);
     
          // Iterating using enhanced for loop
        for (Map.Entry<String, Integer> e : ht.entrySet())
            System.out.println(e.getKey() + " "
                               + e.getValue());
    }
}


Output

vaibhav 20
vishal 10
sachin 30

 Internal Working of Hashtable

Hashtable datastructure is an array of buckets which stores the key/value pairs in them. It makes use of hashCode() method to determine which bucket the key/value pair should map.
The hash function helps to determine the location for a given key in the bucket list. Generally, hashcode is a non-negative integer that is equal for equal Objects and may or may not be equal for unequal Objects. To determine whether two objects are equal or not, hashtable makes use of the equals() method.

It is possible that two unequal Objects have the same hashcode. This is called a collision. To resolve collisions, hashtable uses an array of lists. The pairs mapped to a single bucket (array index) are stored in a list and list reference is stored in the array index.

Hashtable collision

 

Methods of Hashtable

  • K – The type of the keys in the map.
  • V – The type of values mapped in the map.

METHOD

DESCRIPTION

clear() Clears this hashtable so that it contains no keys.
clone() Creates a shallow copy of this hashtable.

compute(K key, BiFunction<? super 

K,? super V,? extends V> remappingFunction)

Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).

computeIfAbsent(K key, Function<? super K,? 

extends V> mappingFunction)

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
contains(Object value) Tests if some key maps into the specified value in this hashtable.
containsKey(Object key) Tests if the specified object is a key in this hashtable.
containsValue(Object value) Returns true if this hashtable maps one or more keys to this value.
elements() Returns an enumeration of the values in this hashtable.
entrySet() Returns a Set view of the mappings contained in this map.
equals(Object o) Compares the specified Object with this Map for equality, as per the definition in the Map interface.
get(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
hashCode() Returns the hash code value for this Map as per the definition in the Map interface.
 isEmpty() Tests if this hashtable maps no keys to values.
keys() Returns an enumeration of the keys in this hashtable.
keySet() Returns a Set view of the keys contained in this map.
merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
 put(K key, V value) Maps the specified key to the specified value in this hashtable.
 putAll(Map<? extends K,? extends V> t) Copies all of the mappings from the specified map to this hashtable.
rehash() Increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently.
remove​(Object key) Removes the key (and its corresponding value) from this hashtable.
size() Returns the number of keys in this hashtable.
 toString() Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters “, ” (comma and space).
 values() Returns a Collection view of the values contained in this map.

Methods declared in interface java.util.Map

METHOD

DESCRIPTION

 forEach(BiConsumer<? super K,? super V> action) Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
getOrDefault(Object key, V defaultValue) Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
putIfAbsent​(K key, V value) If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.

remove​(Object key,

                     Object value)

Removes the entry for the specified key only if it is currently mapped to the specified value.
replace(K key, V value) Replaces the entry for the specified key only if it is currently mapped to some value.
replace(K key, V oldValue, V newValue) Replaces the entry for the specified key only if currently mapped to the specified value.
replaceAll(BiFunction<? super K,? super V,? extends V> function) 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.

Must Read:

Advantages of Hashtable:

  1. Thread-safe: The Hashtable class is thread-safe, meaning that multiple threads can access it simultaneously without causing data corruption or other synchronization issues.
  2. Simple to use: The Hashtable class is simple to use and provides basic key-value data structure functionality, which can be useful for simple cases.

Disadvantages of Hashtable:

  1. Obsolete: The Hashtable class is considered obsolete and its use is generally discouraged. This is because it was designed prior to the introduction of the Collections framework and does not implement the Map interface, which makes it difficult to use in conjunction with other parts of the framework.
  2. Limited functionality: The Hashtable class provides basic key-value data structure functionality, but does not provide the full range of functionality that is available in the Map interface and its implementations.
  3. Poor performance: The Hashtable class is synchronized, which can result in slower performance compared to other implementations of the Map interface, such as HashMap or ConcurrentHashMap.

Reference books:

  1. “Java Collections” by Maurice Naftalin and Philip Wadler. This book provides a comprehensive overview of the Java Collections framework, including the Hashtable class.
  2. “Java in a Nutshell” by David Flanagan. This book provides a quick reference for the core features of Java, including the Hashtable class.
  3. “Java Generics and Collections” by Maurice Naftalin and Philip Wadler. This book provides a comprehensive guide to generics and collections in Java, including the Hashtable class.

Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Hashtable.html



Similar Reads

Hashtable toString() Method in Java
The toString() method in the Hashtable class in Java returns a string representation of the key-value mappings contained in the hashtable. The string is in the form of a comma-separated list of key-value pairs enclosed in curly braces. The toString() method is inherited from the java.util.Hashtable class's parent class, java.util.Dictionary. Here's
2 min read
Hashtable elements() Method in Java
The elements() method in the Hashtable class in Java returns an enumeration of the values contained in the hashtable. The enumeration returned by this method traverses the hashtable's values in the order in which they were added to the hashtable. The elements() method is inherited from the java.util.Hashtable class's parent class, java.util.Diction
2 min read
Hashtable keys() Method in Java
As we all know enumeration defines java class type so do enumerations can have constructors, methods, and instance variables. The java.util.Hashtable.keys() method of Hashtable class in Java is used to get the enumeration of the keys present in the hashtable. Illustration: Syntax: public Enumeration&lt;K&gt; keys() Enumeration enu = Hash_table.keys
2 min read
Hashtable containsValue() Method in Java
The java.util.Hashtable.containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the Hashtable. It takes the Value as a parameter and returns True if that value is mapped by any of the keys in the table. Syntax: Hash_Table.containsValue(Object Value) Parameters: The method takes just one
2 min read
Hashtable containsKey() Method in Java
The java.util.Hashtable.containsKey() method is used to check whether a particular key is present in the Hashtable or not. It takes the key element as a parameter and returns True if that element is present in the table. Syntax: Hash_table.containsKey(key_element) Parameters: The method takes just one parameter key_element which refers to the key w
2 min read
Hashtable put() Method in Java
The java.util.Hashtable.put() method of Hashtable is used to insert a mapping into a table. This means we can insert a specific key and the value it is mapping to into a particular table. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole. Syntax: Hash
3 min read
Hashtable get() Method in Java
The java.util.Hashtable.get() method of Hashtable class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the table contains no such mapping for the key. Syntax: Hash_Table.get(Object key_element) Parameter: The method takes one parameter key_element of object type and refers to the k
2 min read
Hashtable isEmpty() Method in Java
The java.util.Hashtable.isEmpty() method of Hashtable class is used to check for the emptiness of the table. The method returns True if no key-value pair or mapping is present in the table else False. Syntax: Hash_Table.isEmpty() Parameters: The method does not take any parameters. Return Value: The method returns boolean true if the table is empty
2 min read
Hashtable size() Method in Java
The java.util.Hashtable.size() method of Hashtable class is used to get the size of the table which refers to the number of the key-value pair or mappings in the Table. Syntax: Hash_Table.size() Parameters: The method does not take any parameters. Return Value: The method returns the size of the table which also means the number of key-value pairs
2 min read
Hashtable remove() Method in Java
The java.util.Hashtable.remove() is an inbuilt method of Hashtable class and is used to remove the mapping of any particular key from the table. It basically removes the values for any particular key in the Table.Syntax: Hash_Table.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from the Table.Return
2 min read