Junior — Middle
Have you participated in planning and executing sprint tasks in previous projects?
sobes.tech AI
Answer from AI
Yes, in Java, the HashSet data structure is implemented on top of HashMap. Inside HashSet, the set elements serve as keys in a HashMap, and the value for all keys is a common dummy object. This allows efficient element uniqueness enforcement and quick access.
Example of simplified HashSet implementation:
public class MyHashSet<E> {
private transient HashMap<E, Object> map;
private static final Object PRESENT = new Object();
public MyHashSet() {
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;
}
}