Sobes.tech
Junior — Middle

How are HashMap and HashSet data structures related in Java?

sobes.tech AI

Answer from AI

HashSet in Java is implemented based on HashMap. Inside HashSet, each element is stored as a key in the HashMap, and the value for all keys is the same placeholder object (usually a static final object). This allows HashSet to efficiently ensure element uniqueness and quick access, leveraging the capabilities of HashMap.

Example of a simplified HashSet implementation:

public class SimpleHashSet<E> {
    private static final Object PRESENT = new Object();
    private HashMap<E, Object> map = new HashMap<>();

    public boolean add(E e) {
        return map.put(e, PRESENT) == null;
    }

    public boolean contains(E e) {
        return map.containsKey(e);
    }

    public boolean remove(E e) {
        return map.remove(e) == PRESENT;
    }
}