Hashtable Class

Hashtable Class

In this tutorial, we are going to discuss about Hashtable Class in java. The Hashtable class in Java is a legacy data structure that implements the Map interface and extends the Dictionary class.

It provides a key-value pair storage mechanism where both keys and values are objects. It is similar to HashMap, but it is synchronized, making it thread-safe for concurrent access.

Hashtable Class
  • The underlying data structure is Hashtable
  • Insertion order is not preserved and it is based on hash code of the keys.
  • Heterogeneous objects are allowed for both keys and values.
  • null key (or) null value is not allowed otherwise we will get NullPointerException.
  • Duplicate keys are allowed but values can be duplicated.
  • Every method present inside Hashtable is syncronized and hence Hashtable object is Thread-safe.
Constructors

1. Hashtable h=new Hashtable();

Creates an empty Hashtable object with default initialcapacity 11 and default fill ratio 0.75.

2. Hashtable h=new Hashtable(int initialcapacity);

3. Hashtable h=new Hashtable(int initialcapacity,float fillratio);

4. Hashtable h=new Hashtable (Map m);

package com.ashok.collections;

import java.util.Hashtable;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class HashtableExample {
    public static void main(String[] args) {
        // Creating a Hashtable
        Hashtable<String, Integer> hashtable = new Hashtable<>();

        // Adding key-value pairs
        hashtable.put("Ashok", 30);
        hashtable.put("Dillesh", 25);
        hashtable.put("Rama", 35);

        // Accessing values
        System.out.println("Ashok's age: " + hashtable.get("Ashok"));

        // Iterating over entries
        for (String key : hashtable.keySet()) {
            System.out.println(key + " - " + hashtable.get(key));
        }

        // Checking if a key exists
        System.out.println("Does the hashtable contain key 'Dillesh'? " +   hashtable.containsKey("Dillesh"));

        // Removing a key-value pair
        hashtable.remove("Dillesh");

        // Size of the map
        System.out.println("Size of the map: " + hashtable.size());
    }
}

In this example, we create a Hashtable, add key-value pairs, access values, iterate over entries, check for key existence, remove a key-value pair, and get the size of the map. The order of the elements in the Hashtable is not guaranteed.

That’s all about the Hashtable class in java. If you have any queries or feedback, please write us email at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

Hashtable Class
Scroll to top