StackTips

Hashtable in Java

siteadmin avtar

Written by

Stacktips,  3 min read,  558 views, updated on July 24, 2024

The Hashtable is a legacy implementation of HashMap. It provides a key-value store where the keys are hashed. HashMap performs better than Hashtable.

Key Properties of Hashtable

The Hashtable is synchronized, meaning it is thread-safe and can be shared between multiple threads.

Hashtable does not allow null keys or values. If you try to add null as a key or value, it will throw a NullPointerException.

public class _1a_Hashtable {  


    public static void main(String[] args) {  
        Hashtable<Integer, String> hashtable = new Hashtable<>();  
        hashtable.put(1, "One");  
        hashtable.put(2, "Two");  
        hashtable.put(3, "Three");  

        // Retrieve a value by its key  
        String value = hashtable.get(2);  
        System.out.println("Value for key 2: " + value);  

        // Remove a key-value pair  
        hashtable.remove(3);  

        // Check if a key exists  
        boolean containsKey = hashtable.containsKey(1);  
        System.out.println("Hashtable contains key 1: " + containsKey);  

        // Check if a value exists  
        boolean containsValue = hashtable.containsValue("Two");  
        System.out.println("Hashtable contains value 'Two': " + containsValue);  

        // Get the size of the hashtable  
        int size = hashtable.size();  
        System.out.println("Size of hashtable: " + size);  

        // Check if the hashtable is empty  
        boolean isEmpty = hashtable.isEmpty();  
        System.out.println("Is hashtable empty? " + isEmpty);  
    }
}

Getting Started with Spring Boot- Beginner's Guide

This course covers the fundamentals of Spring Boot an you will gain the necessary skills to develop various types of applications using the powerful features of the Spring Boot framework.

>> CHECK OUT THE COURSE

Continue reading..