Junior — Middle
How is the storage of elements in HashSet within the data structure HashMap implemented?
sobes.tech AI
Answer from AI
In Java, the HashSet class 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 static object placeholder (usually PRESENT). Thus, HashSet does not store values, only keys in HashMap, which ensures element uniqueness and fast containment checks.
A simplified example of HashSet's internal structure:
private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT) == null;
}
This allows efficient implementation of add, remove, and contains operations using HashMap's capabilities.