Difference between HashMap and HashTable in Java?

Let’s begin with the similarities of HashMap and HashTable:

  • Both store key and value pairs in a hash table
  • Both declare an object which are both declared as a key
  • The key is hashed, and then this hash is indexed within the hash table it is stored

HashMap vs HashTable

HashMap

  • None-synchronised. Not thread safe, unable to be shared between other threads.
  • Allows for one null key and multiple null values
  • Preferred if thread synchronisation is not needed
  • Performance is high as threads are not required to wait
  • Introduced in 1.2
  • None legacy
  • Not good for multithreaded environments

HashTable

  • Synchronised. Thread safe, can be shared between other threads.
  • Does not allow for null values in key or value
  • Preferred if synchronisation is needed
  • Performance is impacted as waiting for threads
  • Introduced in 1.0
  • Legacy
  • Good for multithreaded environments

HashMap Example

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("apple", 5);
        map.put("banana", 3);
        map.put("orange", 10);

        int value = map.get("banana");
        System.out.println(value); // Output: 3

        map.remove("orange");
        map.put("orange", 8);

        System.out.println(map); // Output: {apple=5, banana=3, orange=8}
    }
}

HashTable Example

import java.util.Hashtable;

public class HashTableExample {
    public static void main(String[] args) {
        Hashtable<String, Integer> table = new Hashtable<>();
        table.put("apple", 5);
        table.put("banana", 3);
        table.put("orange", 10);

        int value = table.get("banana");
        System.out.println(value); // Output: 3

        table.remove("orange");
        table.put("orange", 8);

        System.out.println(table); // Output: {apple=5, banana=3, orange=8}
    }
}

📚 Further Reading & Related Topics

If you’re exploring the differences between HashMap and Hashtable in Java, these related articles will provide deeper insights:

• Mastering Null Handling in Java: Best Practices – Learn how null values are handled in Java collections and how that impacts the usage of HashMap and Hashtable.

• Exploring Java 17’s Enhanced Pseudo-Random Number Generators (PRNG): A Dive into JEP 356 – Understand how Java 17’s updates to core features like random number generation might affect the behavior and performance of collections like HashMap and Hashtable.

Leave a comment

I’m Sean

Welcome to the Scalable Human blog. Just a software engineer writing about algo trading, AI, and books. I learn in public, use AI tools extensively, and share what works. Educational purposes only – not financial advice.

Let’s connect