Home » Java Tutorial » Hashtable in Java

Hashtable in Java




Tags Java

Hashtable class in Java inherits the Dictionary class. Previously it was part of the java.util. From Java 2 onwards, it is part of the Collections framework since it can now implement the Map interface as well. It is similar to HashMap but has a few differences which we will see towards the end of this tutorial. Now we will learn about HastTable in Java.

Hashtable in Java

Hashtable contains entries in the form of key-value. Each key is an object which has a unique value. The Hashtable uses the hashing technique where the key is hashed and uses the resulting hashcode as the index of the key. Both keys and values have to be a non-null value.

It is one of the oldest implementations of the hash table data structure after which the HashMap came into place.

Java Hashtable Constructors

Below are the constructors in the Hashtable in Java.

Constructors Description
Hashtable()Creates an empty Hashtable with default capacity and loadfactor
Hashtable(int capacity)Creates a hashtable with the specified capacity
Hashtable(int capacity, float loadfactor)Creates a hashtable with specified capacity and loadfactor
Hashtable(Map m)Creates a hashtable with mapping of the specified Map

Java Hashtable Methods

Hashtable in Java contains the below methods.

MethodDescriptionParameter
void clear()Clears the hashtable such that it will not have any key-value pairs
Object clone()Creates a shallow copy of the hashtable
String compute(Integer key, BiFunction remappingfunction)Attempts to compute mapping for the specified key and its valuekey - key with which the value is associated
remappingfunction - function which computes the value
String computeIfAbsent(Integer key, Function remappingfunction)If the specified key does not contain any value, it attempts to compute the value using the function and enters itkey - key with which the value is associated
remappingfunction - function which computes the value
String computeIfPresent(Integer key, Function remappingfunction)If the specified key contains a value, it attempts to compute the value using the function and enters itkey - key with which the value is associated
remappingfunction - function which computes the value
boolean contains(Object value)Checks if the hashtable contains a key with the specified valuevalue - value in the hashtable to check if it has a key
boolean containsKey(Object key)Checks if the hashtable contains the specified keykey - key to be checked
boolean containsValue(Object value)Checks if the hashtable contains the specified valuevalue - value to be checked
Enumeration elements()Returns an enumeration of elements in the hashtable
Set entrySet()Returns a set view of the mappings in the hashtable
boolean equals(Object o)Checks if the specified object is equal to the map
void forEach(Consumer action)Performs the specified action for each entry in the hashtableaction - the action to be applied
String get(Object key)Retrieves the value associated with the specified keykey - key for which we need to get the value
String getOrDefault(Object key, String defaultValue)Returns the value for the specified key else returns the default value if there is no mappingkey - key for which we need to get the value
defaultValue - defaultValue if there is no mapping for the key
boolean isEmpty()Checks if the hashtable is empty
Enumeration keys()Returns an enumeration of keys in the hashtable
Set keySet()Returns a set view of the keys in the hashtable
String put(int key, String value)Puts the key with the specified value into the hashtablekey - key to be mapped
value - value associated with the key
void putAll(Map m)Puts all the mapping of the specified map into the hashtablem - map to be copied into the hashtable
String putIfAbsent(Integer key, String value)If the specified key is not associated with the value, it associates with the specified valuekey - key to be mapped
value - value associated with the key
String remove(Object key)Removes the key and its value from the hashtablekey - key that has to be removed with value
boolean remove(Object key, Object value)Removes the entry from the hashtablekey - key to be removed
value - value associated with the key to be removed
String replace(Integer key, String value)Replaces the key in the hashtable only if it contains some valuekey - key that has value
value - value to be replaced
boolean replace(Integer key, String oldvalue, String newvalue)Replaces the entry in the hashtable only if it contains some valuekey - key that has value
oldvalue - old value associated
newvalue - new value to be mapped
void replaceAll(Function function)Replaces all entries in the hashtable with the result of the functionfunction - function output to replace the values or entries
int size()Returns the number of keys in the hashtable
String toString()Returns a string representation of the entries in the hashtable where it displays string as key=value and each entry separated by ","
Collection values()Returns a collection view of the values in the hashtable
READ  Java Continue

Example: Add entries to hashtable in Java

In the below example, we use the put() method to add the entries as key-value pairs into the hashtable. We can also insert a new entry into the hashtable if the specified key is not present using the putIfAbsent() method. The computeIfAbsent uses the function output as a value to create a new entry for the key that is absent in the hashtable.

import java.util.Hashtable;

public class HashtableDemo {

  public static void main(String[] args) {
    Hashtable<Integer, String> h = new Hashtable<Integer, String>();
    h.put(111,"Aditya");
    h.put(222, "Bharat");
    h.put(333, "Chetan");
    h.put(444, "Dev");
    h.put(555, "Harish");
    System.out.println(h);
    h.putIfAbsent(666, "Ganesh");
    System.out.println("Elements in the hashtable after using putIfAbsent:");
    System.out.println(h.toString());
    System.out.println("Elements in the hashtable after using computeIfAbsent:");
    h.computeIfAbsent(777, t -> "Banu");
    System.out.println(h.toString());
    
  }

}
{555=Harish, 444=Dev, 333=Chetan, 222=Bharat, 111=Aditya}
Elements in the hashtable after using putIfAbsent:
{666=Ganesh, 555=Harish, 444=Dev, 333=Chetan, 222=Bharat, 111=Aditya}
Elements in the hashtable after using computeIfAbsent:
{777=Banu, 666=Ganesh, 555=Harish, 444=Dev, 333=Chetan, 222=Bharat, 111=Aditya}

Example: Removing elements from Hashtable in Java

Below is an example to illustrate how to remove elements from hashtable in Java using the remove() method. Suppose we try to remove a key or value that is not present in the hashtable, it just ignores the statement and proceeds to the next line.

import java.util.Hashtable;

public class HashtableDemo {

  public static void main(String[] args) {
    Hashtable<Integer, String> h = new Hashtable<Integer, String>();
    h.put(111,"Aditya");
    h.put(222, "Bharat");
    h.put(333, "Chetan");
    h.put(444, "Dev");
    h.put(555, "Harish");
    System.out.println(h);
    
    h.remove(333);
    h.remove(444, "Dev");
    System.out.println("Elements after remove operation:");
    System.out.println(h);
    
  }

}
{555=Harish, 444=Dev, 333=Chetan, 222=Bharat, 111=Aditya}
Elements after remove operation:
{555=Harish, 222=Bharat, 111=Aditya}

Example: Check and retrieve elements from Hashtable

We can check if a particular value or key is present in Java Hashtable using the contains() or containsKey() or containsValue() method. To retrieve the value of the corresponding key, we can use the get() method or the getOrDefault() method. In the getOrDefault() method, if the search key is not present, then it returns the default value that we pass.

import java.util.Hashtable;

public class HashtableDemo {

  public static void main(String[] args) {
    Hashtable<Integer, String> h = new Hashtable<Integer, String>();
    h.put(111,"Aditya");
    h.put(222, "Bharat");
    h.put(333, "Chetan");
    h.put(444, "Dev");
    h.put(555, "Harish");
    System.out.println(h);
    
    System.out.println("Check if hashtable contains Chetan: " + h.contains("Chetan"));
    System.out.println("Check if hashtable contains Jeeva: " + h.contains("Jeeva"));
    System.out.println("Check if hashtable contains the key 222: " + h.containsKey(222));
    System.out.println("Check if hashtable contains the key 123: " + h.containsKey(123));
    System.out.println("Check if hashtable contains Hari: " + h.containsValue("Hari"));
    System.out.println("Check if hashtable contains Aditya: " + h.containsValue("Aditya"));
    System.out.println("Get the value of key 444: " + h.get(444));
    System.out.println("Get the value of key 222: " + h.getOrDefault(222, "Test"));
    System.out.println("Get the value of key 123: " + h.getOrDefault(123, "Test"));
  
  
    
  }

}
{555=Harish, 444=Dev, 333=Chetan, 222=Bharat, 111=Aditya}
Check if hashtable contains Chetan: true
Check if hashtable contains Jeeva: false
Check if hashtable contains the key 222: true
Check if hashtable contains the key 123: false
Check if hashtable contains Hari: false
Check if hashtable contains Aditya: true
Get the value of key 444: Dev
Get the value of key 222: Bharat
Get the value of key 123: Test

Example: Iterate through elements in the hashtable in Java

The below example shows how to iterate or retrieve keys and values from the hashtable in Java. The Enumeration and the values() method returns all the values in the hashtable. The entrySet() method returns both the key-value pairs. The keySet() and keys() method retrieves all the keys present in the hashtable.

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

public class IterateHashtable {

  public static void main(String[] args) {
    Hashtable<Integer, String> h = new Hashtable<Integer, String>();
    h.put(111,"Aditya");
    h.put(222, "Bharat");
    h.put(333, "Chetan");
    h.put(444, "Dev");
    h.put(555, "Harish");
    
    System.out.println("Size of hashtable: " + h.size());
    
    Enumeration<String> e = h.elements();
    System.out.println("\nIterate using Enumeration:");
    while(e.hasMoreElements())
      System.out.print(e.nextElement() + " ");
    
    System.out.println();
    System.out.println("\nIterate using Entryset:");
    Set<Entry<Integer, String>> s = h.entrySet();
    System.out.println(s);
    
    System.out.println("\nIterate using Keys:");
    Enumeration<Integer> e1 = h.keys();
    while(e1.hasMoreElements())
      System.out.print(e1.nextElement() + " ");
    
    System.out.println();
    System.out.println("\nIterate using KeySet:");
    Set<Integer> s1 = h.keySet();
    System.out.println(s1);
    
    System.out.println("\nIterate using values:");
    System.out.println(h.values());
  
  }

}
Size of hashtable: 5

Iterate using Enumeration:
Harish Dev Chetan Bharat Aditya 

Iterate using Entryset:
[555=Harish, 444=Dev, 333=Chetan, 222=Bharat, 111=Aditya]

Iterate using Keys:
555 444 333 222 111 

Iterate using KeySet:
[555, 444, 333, 222, 111]

Iterate using values:
[Harish, Dev, Chetan, Bharat, Aditya]

Example: Replace values in a hashtable

The replace() method replaces the old value with the new value if the search key is present. It ignores and proceeds to the next line if the key is not present. This is the reason that the value for the key 123 is not replaced since the key is not present.

import java.util.Hashtable;

public class HashtableDemo {

  public static void main(String[] args) {
    Hashtable<Integer, String> h = new Hashtable<Integer, String>();
    h.put(111,"Aditya");
    h.put(222, "Bharat");
    h.put(333, "Chetan");
    h.put(444, "Dev");
    h.put(555, "Harish");
    System.out.println(h);
    
    h.replace(333, "Chandru");
    h.replace(444, "Dev", "Devi");
    
    h.replace(123, "aaa");
    
    System.out.println(h.toString());
  }

}
{555=Harish, 444=Dev, 333=Chetan, 222=Bharat, 111=Aditya}
{555=Harish, 444=Devi, 333=Chandru, 222=Bharat, 111=Aditya}

Example: Empty or clear all entries in the hashtable

We can empty or clear all the entries in the hashtable using the clear() method. To check if the hashtable is empty, we can use the isEmpty() method.

import java.util.Hashtable;

public class HashtableDemo {

  public static void main(String[] args) {
    Hashtable<Integer, String> h = new Hashtable<Integer, String>();
    h.put(111,"Aditya");
    h.put(222, "Bharat");
    h.put(333, "Chetan");
    h.put(444, "Dev");
    h.put(555, "Harish");
    System.out.println(h);
    
    h.clear();
  
    System.out.println(h.toString());
    System.out.println("Is hashtable empty: " + h.isEmpty());
    
  }

}
{555=Harish, 444=Dev, 333=Chetan, 222=Bharat, 111=Aditya}
{}
Is hashtable empty: true

 

READ  Iterator in Java

Difference between Hashtable and HashMap

Now that we know what is a hashtable and hashmap, let’s see the differences between both.

HashMapHashtable
It is not synchronizedIt is synchronized
It is not thread safe and cannot be shared between threadsIt is thread safe and can be shared between threads
Allows one null key and multiple null valuesDoes not allow null key and null value
Introduced in JDK 1.2It is a legacy class
We use Iterator to traverse through HashmapWe use Iterator or Enumeration to traverse through Hashtable
Inherits AbstractMap classInherits Dictionary class
Computation is fastComputation is slow

Reference

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions

AD Blocker Detected !

Advertisements help running this website for free.

To view the content please disable AdBlocker and refresh the page.

Wait !!!

You can Crack Technical Interviews of Companies like Amazon, Google, LinkedIn, Facebook, PayPal, Flipkart, etc

Anisha was able to crack Amazon after practicing questions from TutorialCup