Sobes.tech
Junior

What is the difference between HashMap and HashSet?

sobes.tech AI

Answer from AI

HashMap: stores key-value pairs. Based on a hash table for quick access. Keys are unique, values can repeat.

HashSet: stores only unique elements. Essentially implemented on top of HashMap, where elements are stored as keys, and a dummy value (e.g., new Object()) is used as the value. Does not guarantee element order.

Main differences:

Characteristic HashMap HashSet
Storage Key-value pairs Unique elements
Implementation Hash table Based on HashMap
Repetitions Keys are unique, values are not Elements are unique
Interface Map Set
// Example of using HashMap
import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> ages = new HashMap<>();
        ages.put("Alice", 30);
        ages.put("Bob", 25);
        ages.put("Alice", 31); // Overwrites the value for "Alice"

        System.out.println(ages.get("Bob")); // 25
    }
}
// Example of using HashSet
import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> names = new HashSet<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Alice"); // Will not be added again, as "Alice" already exists

        System.out.println(names.contains("Bob")); // true
    }
}