View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

What is Hashtable in Java? Explained with Examples

By Pavan Vadapalli

Updated on Jun 23, 2025 | 17 min read | 8.04K+ views

Share:

Did you know that Java is ranked fourth among the top programming languages in 2025? As Java continues to dominate in enterprise environments, understanding data structures like what is a Hashtable becomes essential for developing high-performance applications in multi-threaded contexts.

A Hashtable in Java is a synchronized data structure that stores key-value pairs using a hashing technique. It ensures thread safety in concurrent environments by determining the index for storing values, making it efficient for lookups. 

Unlike HashMap, it doesn’t allow null keys or values, and its iteration order is not guaranteed. Understanding what is a Hashtable is crucial for implementing thread-safe data structures in Java applications, particularly for legacy systems or simple multi-threaded use cases.

In this blog, we will explore what is a hashtable in Java, along with examples that are relevant within enterprises. 

Looking to strengthen your Java programming skills? Explore upGrad’s Software Engineering courses with hands-on projects and expert mentorship to master Java fundamentals, including hash map, hash table, and core programming concepts. Enroll now!

What is a Hashtable in Java?

A Hashtable is a data structure that stores data as key-value pairs in buckets. Each key is processed through a hash function to generate a hash code. This hash code is then used to determine the bucket index in which the key-value pair will be placed. Internally, the Hashtable maintains an array of these buckets. Each bucket can contain multiple entries in case different keys generate the same hash index, a situation known as a collision.

The Hashtable resolves collisions using chaining. In this technique, each bucket holds a linked list of entries with the same hash index. It allows the structure to manage and retrieve data efficiently even during collisions.

If you want to learn Java and other programming languages for modern enterprise operations, the following courses from upGrad can help you succeed.

What Is a Hash Function?

A hash function is a mechanism that takes a key and returns a numerical hash code. This number determines where in the array the data should be stored. The quality of the hash function used determines the effectiveness of a hash table.

A good hash function should:

  • Be quick and efficient in computing
  • Distribute keys evenly across the available buckets
  • Minimize the number of collisions

How is a Hash Function chosen in a hash table?

The hash function determines where each key-value pair will be stored in a hash table. It takes a key and converts it into a fixed-size integer called a hash code, which is then used to compute the bucket index where the entry will be placed.

Java provides a built-in method called hashCode() that returns an integer hash for each object. However, what matters most is not just computing the hash code, but how it is processed and distributed across the bucket array.

Criteria for Choosing a Good Hash Function

A good hash function should satisfy several essential conditions to ensure efficient storage and retrieval:

  • Easy to compute: It should be fast and lightweight. The function must not become a performance bottleneck during frequent insertions or lookups.
  • Uniform distribution: Keys should be distributed evenly across all available buckets. This minimizes the chance that many entries land in the same bucket, which would increase lookup time.
  • Minimize collisions: A well-designed hash function reduces the chances of two distinct keys producing the same bucket index. Although collisions are inevitable, fewer collisions mean better performance.

Both Hashtable and HashMap serve similar purposes, but they have distinct differences you should know. Let's explore the key differences between Hashtable and HashMap and when to use each.

Hashtable vs HashMap in Java: Key Differences

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

Both Hashtable and HashMap rely on hashing code in Java to store key-value pairs efficiently, but their concurrency handling and usage contexts differ significantly. While ReactJS developers might often interact with Java backends, understanding these distinctions is critical when dealing with data caching or session management in full-stack applications. 

Although both classes use a hash table to store key-value pairs, they differ in some crucial aspects:

Feature Hashtable HashMap
Thread Safety
  • Synchronized internally with coarse-grained locking, causing slower performance in high concurrency.
  • Suitable for legacy multi-threaded environments without external synchronization.
  • Not synchronized by default; can be wrapped with Collections.synchronizedMap() for thread safety. 
  • For high concurrency, ConcurrentHashMap offers fine-grained locking and superior scalability.
Null Support
  • Does not allow null keys or null values, preventing NullPointerExceptions in legacy code.
  • Allows one null key and multiple null values, offering more flexibility in data handling.
Iteration Behavior
  • Iterators are not fail-fast, meaning concurrent modifications might go undetected, potentially causing inconsistent behavior.
  • Fail-fast iterators throw ConcurrentModificationException on concurrent modification, aiding safer iteration.
Performance
  • Slower due to synchronized methods and locking overhead; not suitable for performance-critical or highly concurrent modern applications.
  • Generally faster with better throughput; supports external synchronization or concurrent alternatives for thread-safe use.
Legacy vs Modern Use
  • Part of Java’s legacy collections; primarily used for backward compatibility in older systems where synchronized maps were essential.
  • Core component of the modern Collections Framework; recommended for most new Java applications and frameworks integrating backend APIs with frontend tools like ReactJS.
Use Case Scenarios
  • Useful when maintaining legacy applications requiring thread-safe hash tables without refactoring.
  • Ideal for new development needing flexible null handling, better performance, and scalable concurrency control.

Example Scenario:

You maintain a legacy financial system that relies on Hashtable for thread-safe caching without refactoring. Migrating to HashMap requires extensive code changes and synchronization adjustments. Continuing with Hashtable ensures stability and backward compatibility while new systems adopt modern concurrent collections.

Enhance your Java skills by mastering core data structures like hash tables. Learn how to work with key-value pairs, optimize performance, and write cleaner code. Enroll in the free Java Object-Oriented Programming course today and take your Java applications to the next level.

Also Read: What is Hashing in Data Structures? Explore Hashing Techniques, Benefits, Limitations, and More

Now that you know what a hashtable is and how it compares to HashMap, let's explore its efficiency.

How Does a Hashtable Work Internally? An Example

Understanding a Hashtable in Java requires knowledge of its internal structure and behavior. It does not maintain any specific order of the elements. Compared to HashMap, a Hashtable is synchronized, making it thread-safe for concurrent environments. The default initial capacity of a Hashtable is 11, and the load factor (or fill ratio) is 0.75, which determines when the table should resize to maintain performance.

Syntax:

Hashtable<key, val> ht = new Hashtable<key, val>();

Constructors:
Several constructors are available in Java to create a Hashtable object, allowing you to define the initial capacity and load factor based on your specific needs. Java uses default values—initial capacity of 11 and load factor of 0.75 if not specified. These constructors help optimize performance depending on the expected number of entries and the desired trade-off between memory usage and rehashing frequency.

Below are the constructors to create a Hashtable object.

1. HashTable(): It will create a HashTable with an initial capacity of 11 and a load factor of 0.75

Hashtable<key, val> ht = new Hashtable<key, val>();

2. HashTable(int initialCapacity): It will create a HashTable with a defined initial capacity and a default load factor of 0.75

Hashtable<key, val> ht = new Hashtable<key, val>(int initialCapacity);

3. HashTable(int size, float fillRatio): It will create a HashTable with a defined size and fill ratio

Hashtable<key, val> ht = new Hashtable<key, val>(int size, float fillRatio);

Quick Tips for Choosing Parameters:

  • If your application expects many insertions, increase the initial capacity to minimize resizing.
  • Choose a load factor around 0.75 to balance memory consumption and collision rate.
  • Consider a higher load factor for memory-sensitive applications, but be aware that it might affect lookup speed.

Each constructor serves different scenarios, and choosing the right one ensures efficient use of the hashtable in Java for your specific requirements.

Below is an example of adding and printing Hashtable items. Let’s understand it through a practical example.

Sample Code:

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

public class Example {
    public static void main(String[] args) {

        Hashtable hashtable = new Hashtable();

        // Adding an element to Hashtable.
        hashtable.put("one", "Nitin");
        hashtable.put("two", "Saurabh");
        hashtable.put("three", "Rahul");

        /*
         * Display HashTable entries using Entry Set.
         */
        Set entries = hashtable.entrySet();
        for(Entry entry : entries){
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }

        System.out.println(hashtable);
    }
}

Code Explanation:

  • Hashtable Creation: The program starts by creating a new object using Java's built-in Hashtable class. This data structure stores key-value pairs and ensures that each key is unique. The keys and values in this example are both strings.
  • Adding Elements to the Hashtable: The put() method inserts entries into the hashtable. Each entry consists of a unique key and its associated value. In this case:
  • "one" is associated with "Nitin",
  • "two" with "Saurabh",
  • "three" with "Rahul".
  • Using Entry Set for Iteration: The program uses the entryset () method to access and display each entry in the hashtable. This method returns a set of maps. Entry objects, each holding a key-value pair. The program can print each entry individually in a readable format (key -> value) by iterating over this set.
  • Printing Key-Value Pairs: The program uses getKey() and getValue() to extract and display each pair inside the loop. This gives a clear view of what data the hashtable currently holds, and it separates logic from structure, improving readability.
  • Printing the Entire Hashtable: The program prints the hashtable object directly after listing all entries individually. This uses the toString() method of Hashtable, which outputs all entries in {key=value, ...} format. It provides a quick overview of the hashtable’s contents in one line.

Output: It's important to note that a Hashtable in Java does not maintain insertion order. So, even though the entries were added in a specific order, the printed output may appear differently.

two -> Saurabh
one -> Nitin
three -> Rahul
{two=Saurabh, one=Nitin, three=Rahul}

Output Explanation:
The output shows that a Hashtable in Java does not preserve the order of insertion. Even though the entries were added in a specific order, they appear differently when printed.

Master Java Fundamentals with Confidence. Learn to work with core data structures like Hashtable, manage key-value pairs, and handle real-world input scenarios effectively. Enroll in upGrad’s free Core Java Basics course today and build smarter, more efficient Java programs.

Also Read: For-Each Loop in Java [With Coding Examples]

Now that we’ve covered how to create hashtables, let’s look at the common operations you can perform on a hash table Java, including examples.

Common Hashtable Operations and Key Methods in Java

Hashtable provides a rich set of methods that let you perform various operations, from basic insertion and retrieval to more advanced concurrent programming patterns. Understanding these methods will help you manage data efficiently and avoid common pitfalls.

Below is a table summarizing the key Hashtable methods, their purposes, and when to use them:

Method

Description

put(K key, V value) Inserts or updates the key-value pair in the hashtable.
get(Object key) Retrieves the value associated with the specified key, or null if none exists.
remove(Object key) Removes the key and its corresponding value from the hashtable.
containsKey(Object key) Checks if a given key exists in the hashtable.
containsValue(Object value) Checks if a specified value is present in the hashtable.
size() Returns the number of key-value pairs currently in the hashtable.
clear() Removes all key-value pairs from the hashtable.
clone() Creates a shallow copy of the hashtable.
compute(K key, BiFunction remappingFunction) Attempts to compute a new mapping for the specified key and its current value. Useful for atomic updates.
computeIfAbsent(K key, Function mappingFunction) Computes and inserts a value if the specified key is not already associated with a value. Ideal for lazy initialization.
computeIfPresent(K key, BiFunction remappingFunction) Computes a new value for a key only if it is already present. Useful for conditional updates.
putIfAbsent(K key, V value) Inserts the key-value pair only if the key is not already associated with a value. Helps avoid overwriting existing entries.
replace(K key, V value) Replaces the value for the specified key only if it currently maps to some value.
replace(K key, V oldValue, V newValue) Replaces the value for the specified key only if currently mapped to the specified old value.
contains(Object value) Tests if some key maps to the specified value in the hashtable.
elements() Returns an enumeration of all the values in the hashtable.
entrySet() Returns a Set view of the mappings contained in this hashtable.
isEmpty() Checks if the hashtable contains no key-value pairs.
keys() Returns an enumeration of all the keys in the hashtable.
keySet() Returns a Set view of the keys contained in this hashtable.
putAll(Map<? extends K, ? extends V> t) Copies all mappings from the specified map into the hashtable.
rehash() Increases the capacity and reorganizes the hashtable internally to maintain efficient access. This can be costly in time and should be minimized. Poorly implemented hash functions may lead to excessive rehashing or even infinite loops, so designing good hashCode() methods is critical.
toString() Returns a string representation of the hashtable’s contents.
values() Returns a Collection view of the values contained in the hashtable.

Key Method Usage Insights

  • rehash(): This method is automatically triggered when the Hashtable’s load factor threshold is reached, resizing internal buckets to optimize hashing code in Java and reduce collisions. Like CSS minimizing browser redraws, rehashing improves access speed, but frequent resizing may cause delays. Setting appropriate initial capacity and load factor helps balance performance and memory.
  • putIfAbsent(): Ideal for multi-threaded contexts, this method atomically adds a key-value pair only if the key is missing, preventing overwrites without external locks. Like HTTP’s PUT requests, it ensures safe updates without unintended side effects in concurrent environments.
  • computeIfAbsent(): Commonly used for lazy initialization, this method computes and inserts a value only when the key is absent, improving efficiency in cache-like structures. Like dynamic HTML content that loads on demand, it avoids unnecessary computation and supports thread-safe population of Hashtable entries.

To enhance your Java expertise and build advanced cloud engineering skills, explore upGrad’s Master the Cloud and Lead as an Expert Cloud Engineer. This program integrates Java with cloud technologies, offering hands-on experience with cloud platforms, architecture, and deployment, preparing you for a successful career in cloud engineering.

Also Read: Computer Networking Basics: Key Concepts, Types, and Benefits Explained

Strengthen your problem-solving skills by learning essential data structures and algorithms. Write efficient, scalable code through expert guidance and real-world practice. Enroll in upGrad’s free Data Structures and Algorithms course today and take your development career to the next level.

Let’s explore some of the advantages and disadvantages of Hashtable Java to explain what is a hashtable and its efficacy in computational operations.

Advantages and Disadvantages of Hashtable

The Hashtable class in Java provides synchronized key-value storage, making it thread-safe for basic concurrent access. However, its legacy design and coarse-grained locking lead to performance bottlenecks in modern containerized environments using Docker and orchestration platforms like Kubernetes. For scalable microservices deployed in Kubernetes clusters, finer concurrency controls provided by ConcurrentHashMap are preferred.

Here’s a tabular format to address the advantages and disadvantages of a Hashtable. 

Aspects Advantages Disadvantages
Thread Safety Built-in synchronization ensures safe concurrent access. Coarse-grained locking causes contention and slows performance on multi-core systems.
Usage Simplicity Simple API for key-value storage, easy for legacy use. Lacks flexibility for advanced concurrency control.
Legacy Compatibility Compatible with older Java codebases. Outdated compared to modern collections like HashMap and ConcurrentHashMap.
Null Handling Disallows null keys and values, avoiding null errors. Restricts use cases needing null support; HashMap allows null keys and values.
Performance Works well in low-concurrency or single-threaded apps. Synchronization overhead reduces throughput in high-concurrency, containerized environments.
Concurrency & Scalability Suitable for basic multithreading. Poor scalability on multi-core and high-concurrency workloads versus ConcurrentHashMap.
Iterator Behavior Supports legacy Enumeration without fail-fast checks. Iterators are not fail-fast, risking inconsistent data during concurrent modifications.

Let’s explore some practical scenarios where a hash table in Java is used. 

Practical Scenario: Where Is a Hashtable Used in Java?

In real-world software development, a Hashtable in Java is used for safe access to shared data across threads. It's particularly useful in older systems requiring built-in synchronization, such as user session tracking, credential validation, and caching configuration settings in concurrent environments.

Example Scenario: Login Authentication System

Imagine you're building a user authentication module for an enterprise application. You need a fast and secure way to look up a username and validate the password. 

You can store usernames as keys and passwords as values in a Hashtable. Since multiple users may log in simultaneously, thread safety is essential, making Hashtable a fitting choice.

Hashtable<String, String> credentials = new Hashtable<>();

// Adding users
credentials.put("admin", "admin123");
credentials.put("john_doe", "pass456");
credentials.put("alice", "alice789");

// Validating login
String username = "john_doe";
String password = "pass456";

if (credentials.containsKey(username) && credentials.get(username).equals(password)) {
    System.out.println("Login successful!");
} else {
    System.out.println("Invalid username or password.");
}

Code Explanation: This Java code demonstrates a simple login validation system using a Hashtable. It first creates a Hashtable to store predefined usernames and passwords as key-value pairs. Then, it simulates a login attempt by setting a username and password. 

The program checks if the username exists in the hashtable and whether the provided password matches the stored one. If both conditions are met, it prints "Login successful!"; otherwise, it prints "Invalid username or password." This example shows how a Hashtable in Java can be effectively used for quick and thread-safe data lookups in authentication scenarios.

Output:
Login successful!

Why Use a Hashtable Here?

  • Fast lookup: O(1) time complexity for get and put operations.
  • Thread safety: Multiple users can safely access or modify the hashtable simultaneously.
  • Simplicity: Easy to implement and understand for basic credential checking.

Practical Use Cases of Hashtable in Java 

Hashtable in Java is commonly found in legacy systems and older enterprise applications for tasks like storing user credentials, managing session data, caching configuration values, or handling metadata. Although modern applications often prefer ConcurrentHashMap for better performance, Hashtable remains useful when simplicity and built-in thread safety are sufficient.

  • User Authentication Systems: It stores and quickly verifies user credentials such as usernames and passwords in a secure, thread-safe way. It allows multiple users to log in simultaneously without data corruption, making it ideal for backend authentication modules in concurrent environments.
  • Caching in Web Applications: Helps store frequently accessed data like configuration settings, translation keys, or recently viewed items. Since Hashtable supports thread-safe operations, it can be used for basic shared caching layers where multiple threads read/write cache data.
  • Session Management in Legacy Systems: Hashtable has often been used in older enterprise Java systems to manage user sessions by associating session IDs with user objects. The synchronized nature ensures reliable session tracking across concurrent HTTP requests.
  • Header/Metadata Storage in Web Servers: Stores HTTP request or response headers and metadata such as content types, tokens, or user-agent strings. This centralized, synchronized access to request info is crucial when multiple threads handle different parts of the request-response cycle.
  • Real-Time Data Synchronization: A Hashtable in Java can manage shared game states or user message implications, such as multiplayer games or live chat systems. Multiple threads can safely access and update the same dataset without risking inconsistency.
  • Compiler Symbol Tables: Compilers must map variable names to types, memory addresses, or scope levels during compilation. Hashtable provides a fast and synchronized way to manage this mapping during lexical or semantic analysis phases.
  • Configuration Lookup Tables: These map keys, like error codes, to messages or environment variables to their values. This helps in centralizing application settings or constants, allowing easy access and management in a thread-safe way.

To enhance your understanding of AI and machine learning for advanced Java functions for implementing hash tables. Check out upGrad’s Executive Diploma in Machine Learning & AI. The program allows you to gain valuable insights on algorithms, SQL for enterprise-grade Java tasks.

Also read: Differences Between HashMap and HashTable in Java

Let’s explore some of the best practices for the Hashtable in Java applications to comprehensively understand what is a hashtable. 

Best Practices for Effectively Using Hashtable in Java Development

When choosing a Hashtable in Java, it’s crucial to understand its strengths and limitations, especially in multi-threaded applications. While Hashtable provides thread safety through synchronized methods. it may introduce performance bottlenecks in high-concurrency scenarios compared to alternatives like ConcurrentHashMap. Using a Hashtable effectively requires careful handling of null values, iteration behavior, and awareness of its legacy status in modern Java development

  • Use When Thread Safety is Needed but Simplicity Suffices: Hashtable’s synchronized methods make it a straightforward choice for simple concurrent access, but it might not be the most efficient.
  • Prefer ConcurrentHashMap for High-Concurrency Scenarios: ConcurrentHashMap offers finer-grained locking and higher throughput for better performance in multithreaded applications.
  • Avoid Null Keys and Values: Since Hashtable does not support nulls, always check data before insertion to prevent NullPointerException.
  • Consider Alternatives for New Projects: In most modern Java applications, HashMap or ConcurrentHashMap are preferred unless you have legacy code or specific synchronization requirements.
  • Mind Iterator Behavior: When iterating over a Hashtable, remember that its enumerators are not fail-fast. Be cautious when modifying the hashtable during iteration to avoid inconsistent results.

If you want to learn advanced software development with Java and other programming languages with AI, check out upGrad’s Generative AI Mastery Certificate for Software Development. The program provides you with expertise to utilize AI-powered coding, debugging, and optimizing development workflows.

How Can upGrad Help You Learn Java and Data Structures?

Understanding Hashtable in Java is crucial for managing key-value pairs in multi-threaded environments with thread safety. It provides synchronized access and fast lookups, useful for authentication, configuration management, and legacy support. While ConcurrentHashMap offers better performance, Hashtable helps build a solid foundation in Java’s collection framework.

To deepen your knowledge and practical skills, upGrad offers specialized Java and data structures programs that cover essential concepts and advanced techniques. These additional courses prepare you to tackle complex coding challenges and optimize application data management.

Curious which course can help you in upskilling in Java proficiency? Contact upGrad for personalized counseling and expert guidance. For hands-on learning, you can also visit your nearest upGrad offline center.

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Source:
https://www.techrepublic.com/article/tiobe-index-language-rankings/

Frequently Asked Questions (FAQs)

1. Can I control the load factor or resize behavior in a Hashtable like I can in a HashMap?

2. What’s the memory impact of using Hashtable compared to other Map implementations?

3. Can I store null keys or null values in a Hashtable?

4. When should I choose Hashtable over HashMap or ConcurrentHashMap?

5. How do I iterate over entries in a Hashtable, and is it safe in concurrent code?

6. I see people say Hashtable is obsolete. Should I avoid using it entirely?

7. What happens if two keys in a Hashtable have the same hashCode?

8. Is it possible to customize the hashing behavior in a Hashtable?

9. I want to serialize a Hashtable to save it. Is it serializable by default?

10. How is Hashtable different from HashMap beyond synchronization?

11. Can I use a Hashtable in Java for implementing a cache system?

Pavan Vadapalli

900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s...

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad KnowledgeHut

upGrad KnowledgeHut

Angular Training

Hone Skills with Live Projects

Certification

13+ Hrs Instructor-Led Sessions

upGrad

upGrad

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks