Difference Between HashSet and HashMap in Java

In this short article, we will discuss the differences between HashMap and HashSet in Java.

While both HashSet and HashMap are two of the most used collections in Java and are part of the Java Collections Framework, there are several key differences between them.

Difference Between HashSet and HashMap in Java

Interface Implementation

HashSet implements the Set interface while HashMap implements the Map interface. The Set interface extends the Collection interface, but the Map interface is an entirely separate one.

Storage Mechanism

HashSet stores single objects, while HashMap stores key-value pairs (entries). This implies that HashMap needs two objects for every insert operation - one is the key, and the other is the value.

Null Elements

HashSet allows one null value, but HashMap allows one null key and multiple null values. 

Duplicates

HashSet does not allow duplicate values. If you try to add a duplicate, it will not throw an error, but the add() method will return false. However, HashMap allows duplicate values, but not duplicate keys.

Ordering: 

Both HashSet and HashMap do not guarantee any specific order of their elements. If you need ordered data, you would use LinkedHashMap or LinkedHashSet. 

Performance: 

For HashSet, operations like add, remove, contains, size, etc. are constant time O(1) operations. HashMap also performs these operations at constant time O(1). 

Usage: 

HashMap is generally used when we need to store data in key-value pairs. HashSet is used when we want to store unique elements and don't care about the order.

Internal working

The HashSet internally uses a HashMap to back its implementation. The objects you insert in HashSet are actually keys to this backing HashMap object, and since all keys in a HashMap are unique, you effectively have a collection of unique elements.

Example

Here is a simple illustration of the differences between HashSet and HashMap:

import java.util.*;

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

        // Create a HashMap
        Map<String, String> map = new HashMap<>();
        map.put("one", "first");
        map.put("two", "second");
        map.put("three", "third");
        System.out.println("HashMap: " + map);

        // Create a HashSet
        Set<String> set = new HashSet<>();
        set.add("first");
        set.add("second");
        set.add("third");
        System.out.println("HashSet: " + set);
    }
}

Output:

HashMap: {one=first, two=second, three=third}
HashSet: [third, first, second]

Similarities Between HashMap And HashSet In Java

Backend Data Structure: Both HashMap and HashSet are backed by a hash table data structure. This allows for fast lookup, insertion, and deletion operations. 

Null Values: Both HashMap and HashSet allow null values. However, while HashMap allows one null key and multiple null values, HashSet allows only one null value. 

Unordered Elements: Both HashMap and HashSet do not guarantee any specific order of their elements. The elements are not stored in the order they were inserted, and you cannot predict the order of the elements when iterating over the collection. 

Thread-safety: Both HashMap and HashSet are not synchronized, which means they are not thread-safe. If they are accessed by multiple threads simultaneously, and at least one of these threads modifies the structure of the HashMap or HashSet, the results are unpredictable. 

Performance: The basic operations like add, remove, contains, and size can be performed in constant time for both HashMap and HashSet

Implementation: The HashSet is internally implemented using a HashMap. It creates a HashMap and if you insert an element into the HashSet using the add() method, the HashSet will internally invoke put() on its backing HashMap with the element you have specified as its key and a constant called PRESENT as its value.

Cheat Sheet: Difference Between HashSet and HashMap in Java

Related Interview QA

Comments