Hashtable

java.util.Hashtable – Hashtable Java Example

In this example, we will show the range of functionality provided by the java.util.Hashtable hashtable Java class. Hashtable was part of the original java.util and is a concrete implementation of a Dictionary. However, with the advent of collections, Hashtable was reengineered to also implement the Map interface. Thus, Hashtable is now integrated into the Collections Framework. It is similar to HashMap, but is synchronized.

1. What is Hashtable in Java

Like HashMap, Hashtable stores key/value pairs in a hash table. However, neither keys nor values can be null. When using Hashtable, you specify an object that is used as a key and the value that you want to be linked to that key.

To store and retrieve objects from a hashtable, the objects used as keys must implement hashCode() and equals() methods. The hashCode() method must compute and return the hash code for the object. Of course, equals() compares two objects. Fortunately, many of Java’s built-in classes already implement the hashCode() method.

An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is the capacity at the time the hash table is created. Note that the hash table is open: in the case of a “hash collision”, a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.

Let us look at the class hierarchy of Hashtable.

Hashtable Java
Fig 1. Hashtable

We can notice that Hashtable extends java.util.Dictionary, that is obsolete now. New implementation should hence implement the Map interface instead, rather than extending this class.

2. Method and constructors

Let us see some of the commonly used constructors and methods of Hashtable. The constructors are:

  • Hashtable(): Constructs a new, empty hashtable with a default initial capacity (11) and load factor (0.75)
  • Hashtable(int initialCapacity): Constructs a new, empty hashtable with the specified initial capacity and default load factor (0.75)
  • Hashtable(int initialCapacity, float loadFactor): Constructs a new, empty hashtable with the specified initial capacity and the specified load factor
  • Hashtable(Map t): Constructs a new hashtable with the same mappings as the given Map

Some of the commonly used methods are:

  • boolean contains(Object value): Tests if some key can map into the specified value in this hashtable
  • boolean containsKey(Object key): Tests if the specified object is a key in this hashtable
  • boolean containsValue(Object value): Returns true if this hashtable maps one or more keys to this value
  • Enumeration elements(): Returns an enumeration of the values in this hashtable
  • Set<Map.Entry<K,V>> entrySet(): Returns a Set view of the mappings contained in this map
  • boolean equals(Object o): Compares the specified Object with this Map for equality, as per the definition in the Map interface
  • V get(Object key): Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key
  • V 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
  • boolean isEmpty(): Tests if this hashtable maps no keys to values
  • Enumeration keys(): Returns an enumeration of the keys in this hashtable
  • Set<K> keySet(): Returns a Set view of the keys contained in this map
  • V put(K key, V value): Maps the specified key to the specified value in this hashtable
  • void putAll(Map<? extends K, ? extends V> t): Copies all of the mappings from the specified map to this hashtable
  • V 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
  • protected void rehash(): Increases the capacity of and internally reorganizes this hashtable, in order to accommodate and access its entries more efficiently
  • V remove(Object key): Removes the key (and its corresponding value) from this hashtable
  • boolean remove(Object key, Object value): Removes the entry for the specified key only if it is currently mapped to the specified value
  • V replace(K key, V value): Replaces the entry for the specified key only if it is currently mapped to some value
  • boolean replace(K key, V oldValue, V newValue): Replaces the entry for the specified key only if currently mapped to the specified value

3. Hashtable Java class example

Let us now check the usage of the methods with an example. One important point: Hashtable does not directly support iterators. Thus, we need to use an enumeration to display the contents of balance.

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Set;
import java.util.Map;
import java.util.Iterator;

public class JavaHashTableExample {
    public static void main (String args[]){
        Enumeration names;
        
        Hashtable <String, Double> balance = new Hashtable<>();
        balance.put("John",3234.50);
        balance.put("Jack",2454.50);
        balance.put("Ryan",5341.50);
        balance.put("Pete",1298.50);
        balance.put("Tom",2458.50);
        balance.put("Ron",5341.50);
        
        // to fetch the keys
        names = balance.keys();
        System.out.println("Keys are :");
        while(names.hasMoreElements()){
            System.out.print(names.nextElement() + " ");
        }
        System.out.println();
        // to fetch only the values using Enumeration
        names = balance.elements();
        System.out.println("Values are :");
        while(names.hasMoreElements()){
            System.out.print(names.nextElement() + " ");
        }
        
        System.out.println();        
        System.out.println("Hashtable contains a key Jack? : "+balance.containsKey("Jack"));
        System.out.println("Hashtable contains a value 3234.50? : "+balance.containsValue(3234.50));
        System.out.println("Value for key Jack : "+balance.get("Jack"));
        balance.putIfAbsent("Stan",4400.00);

        // to fetch a set view of mappings contained in map
        Set<Map.Entry<String, Double>> balSet = balance.entrySet();
        Iterator iter = balSet.iterator();
        System.out.println();
        System.out.println("Values in Set are:");
        while (iter.hasNext()){
            System.out.print(iter.next() + " ");
        }
                
    }
}

Let’s explain the methods used in the above example.

  • public Hashtable() – Constructs a new, empty hashtable with a default initial capacity (11) and load factor (0.75).
  • public V put(K key, V value) – Maps the specified key to the specified value in this hashtable. Neither the key nor the value can be null. The value can be retrieved by calling the get method with a key that is equal to the original key.
  • public Enumeration keys() – Returns an enumeration of the keys in this hashtable.
  • public V get(Object key) – Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. More formally, if this map contains a mapping from a key k to a value v such that (key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)
  • We can obtain set-views of the hash table, which permits the use of iterators. To do so, you simply use one of the collection-view methods defined by Map, such as entrySet() or keySet()

4. The complexity of operations and comparison with Hashmap

Both Hashtable and HashMap implement the Map interface. There is some difference between the two. Hashtable is synchronized and doesn’t allow any null key or value. Let us check the complexity of some common operations. The average case complexity would be O(1). The worst case would be a scenario where all the keys cause hash collisions. In such a case, the complexity would be O(n).

OperationAverage caseWorst case
getO(1)O(n)
addO(1)O(n)
deleteO(1)O(n)
Complexity of operations table

Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap instead of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap.

5. Download the source code

Download
You can download the source code of this example from here: java.util.Hashtable – Hashtable Java Example

Last updated on May 13th, 2020

Armando Flores

Armando graduated from from Electronics Engineer in the The Public University Of Puebla (BUAP). He also has a Masters degree in Computer Sciences from CINVESTAV. He has been using the Java language for Web Development for over a decade. He has been involved in a large number of projects focused on "ad-hoc" Web Application based on Java EE and Spring Framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button