← Back to Chapters

Hashtable in Advance Java

?️ Hashtable in Advance Java

? Quick Overview

Hashtable is a legacy collection class in Java that stores data in key–value pairs. It is part of java.util package and is synchronized by default, making it thread-safe.

? Key Concepts

  • Stores data as key and value pairs
  • Does not allow null keys or values
  • Synchronized (thread-safe)
  • Uses hashing technique
  • Legacy class (older than HashMap)

? Syntax / Theory

Hashtable works internally using hash tables where keys are converted into hash codes. Based on the hash code, values are stored and retrieved efficiently.

? View Code Example
// Importing Hashtable class
import java.util.Hashtable;

// Main class
public class HashtableDemo {

// Main method
public static void main(String[] args) {

// Creating Hashtable object
Hashtable<Integer, String> ht = new Hashtable<>();

// Adding elements to Hashtable
ht.put(1, "Java");
ht.put(2, "Python");
ht.put(3, "C++");

// Displaying Hashtable
System.out.println(ht);
}
}

? Live Output / Explanation

Output

{3=C++, 2=Python, 1=Java}

The output shows key–value pairs stored inside the Hashtable. Order is not guaranteed because hashing is used.

? Interactive Playground

Simulate put(key, value) and remove(key)

Hashtable is empty

✅ Tips & Best Practices

  • Use Hashtable only when thread-safety is required
  • Prefer HashMap or ConcurrentHashMap for modern applications
  • Avoid legacy classes in new projects

? Try It Yourself

  • Add more key–value pairs and print them
  • Try removing an element using remove()
  • Check if a key exists using containsKey()