What is Hashmap & Hashtable with example?

Hashtabel is original collection classes in java which was introduced as version 1.2 that HashMap permits null values in it, while Hashtable doesn’t.

In advanced Java, HashMap and Hashtable are both data structures that store key-value pairs, but they have some differences.

  1. HashMap:
    • Introduced in Java 1.2 as part of the Java Collections Framework.
    • It allows one null key and multiple null values.
    • It is not synchronized, meaning it is not thread-safe. If multiple threads access a HashMap concurrently and at least one of the threads modifies the map structurally, it must be synchronized externally.
    • It is generally preferred over Hashtable in non-thread-safe scenarios due to its better performance.

    Example of HashMap:

    java
    import java.util.HashMap;

    public class HashMapExample {
    public static void main(String[] args) {
    HashMap<String, Integer> hashMap = new HashMap<>();

    // Adding key-value pairs
    hashMap.put("One", 1);
    hashMap.put("Two", 2);
    hashMap.put("Three", 3);

    // Accessing values
    int value = hashMap.get("Two");
    System.out.println("Value for key 'Two': " + value);

    // Iterating through the entries
    for (String key : hashMap.keySet()) {
    System.out.println(key + ": " + hashMap.get(key));
    }
    }
    }

  2. Hashtable:
    • Introduced in JDK 1.0, it is part of the original Java Collections Framework.
    • It does not allow null keys or null values. If you try to insert null, it will throw a NullPointerException.
    • It is synchronized, making it thread-safe. All of its methods are synchronized, which means it is safe to use in a multi-threaded environment.

    Example of Hashtable:

    java
    import java.util.Hashtable;

    public class HashtableExample {
    public static void main(String[] args) {
    Hashtable<String, Integer> hashtable = new Hashtable<>();

    // Adding key-value pairs
    hashtable.put("One", 1);
    hashtable.put("Two", 2);
    hashtable.put("Three", 3);

    // Accessing values
    int value = hashtable.get("Two");
    System.out.println("Value for key 'Two': " + value);

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

It’s important to choose between HashMap and Hashtable based on the specific requirements of your application. If thread safety is not a concern, HashMap is generally preferred for its better performance. If thread safety is a requirement, then Hashtable or other synchronized collections from the java.util.concurrent package should be considered.