Core Java

HashMap vs Dictionary In Java

In Java, HashMap and Dictionary are both data structures used to store key-value pairs. While they share some similarities, they significantly differ in their design, usage, and behavior. This article explores the differences between these two classes, explaining their features with code examples. It’s HashMap vs Dictionary time folks!

1. What is a HashMap?

A HashMap is part of the java.util package and implements the Map interface. It is a modern and widely used collection for mapping keys to values. A HashMap allows null keys and values and is not synchronized by default.

public class HashmapExample {

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

        // Adding elements
        hashMap.put("Shoes", 3);
        hashMap.put("Shirts", 5);
        hashMap.put("Trousers", 2);

        // Retrieving and displaying elements
        System.out.println("HashMap: " + hashMap);
        System.out.println("Value for 'Shoes': " + hashMap.get("Shoes"));

        // Iterating through the HashMap
        hashMap.forEach((key, value) -> System.out.println(key + " -> " + value));
    }
}

HashMap uses a hash table internally to store entries, making lookups and updates efficient with an average time complexity of O(1). Since it is not synchronized, it is faster than Hashtable and Dictionary in single-threaded scenarios. However, for multi-threaded use, external synchronization is required.

2. What is a Dictionary?

Dictionary is an abstract class in the java.util package. It was the original class used for mapping keys to values in Java, but it is now considered legacy and has been largely replaced by Map-based implementations such as HashMap.

public class DictionaryExample {

    public static void main(String[] args) {
        Dictionary<String, Integer> dictionary = new Hashtable<>();

        dictionary.put("Dog", 1);
        dictionary.put("Cat", 2);
        dictionary.put("Bird", 3);

        System.out.println("Dictionary: " + dictionary);
        System.out.println("Value for 'Cat': " + dictionary.get("Cat"));

        dictionary.keys().asIterator().forEachRemaining(key
                -> System.out.println(key + " -> " + dictionary.get(key))
        );
    }
}

Dictionary is an abstract class, and Hashtable is its primary concrete implementation. Unlike HashMap, Dictionary does not allow null keys or values. It is thread-safe because it synchronizes methods, but this comes at the cost of performance in multi-threaded environments. Its usage is discouraged in modern Java applications.

3. Key Differences Between HashMap and Dictionary

The HashMap class is a more versatile and efficient replacement for Dictionary. It is designed to handle common use cases in modern applications, whereas Dictionary remains in the Java API for compatibility with older codebases.

FeatureHashMapDictionary
Packagejava.utiljava.util
Introduced InJava 2 (JDK 1.2)Java 1 (JDK 1.0)
InheritanceImplements Map interfaceAbstract class
SynchronizationNot synchronizedSynchronized
Null HandlingAllows null keys and valuesDoes not allow nulls
PerformanceFaster in single-threaded scenariosSlower due to synchronization

4. When to Use HashMap vs. Dictionary

Use a HashMap for flexible and high-performance key-value pair management, especially in modern applications where synchronization can be managed externally if necessary. On the other hand, avoid using Dictionary in new code as it is primarily maintained for backward compatibility. For synchronized operations, opt for ConcurrentHashMap as a modern and efficient alternative to Dictionary.

Here is a code example demonstrating the use of ConcurrentHashMap instead of Dictionary.

public class ConcurrentHashMapExample {

    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

        map.put("Red", 10);
        map.put("Blue", 20);
        map.put("Green", 30);

        System.out.println("ConcurrentHashMap: " + map);
    }
}

5. Conclusion

The HashMap and Dictionary classes serve similar purposes, but HashMap is the preferred choice for modern Java development. It provides better performance, flexibility, and compatibility with the Java Collections Framework. On the other hand, Dictionary is a legacy class with limited features and is rarely used today.

6. Download the Source Code

This was an article on the differences between Java HashMap vs. Dictionary.

Download
You can download the full source code of this example here: java hashmap vs dictionary

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button