How does a HashSet use a HashMap internally in Java, and what does that explain?
A HashSet is really a HashMap with a twist. The elements of the set are stored as the keys of the map, and the values of the map are all the same shared object, which is there only so that the map has something to put there.
That one fact explains a lot of the behaviour of a set.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("Ada");
set.add("Grace");
// A set is a map whose values are all the same object.
Map<String, String> map = new HashMap<String, String>();
for (String name : set) {
map.put(name, "PRESENT");
}
System.out.println("set size : " + set.size());
System.out.println("map size : " + map.size());
System.out.println("map value : " + map.get("Ada"));
}
}
So what does it explain? It explains why a set cannot hold the same element twice. The map holds one entry for each key, so putting the same key in again replaces the value rather than adding a second entry. It explains why the order of a set is not promised, because the order comes from the buckets of the map. And it explains why a set has the same rules about the hash code and the equals method that a map has, because the elements of the set are the keys of the map.
The next question in this topic looks at the methods of a set and at what their return values mean.