The Set
and Map
interfaces are not related (with the exception of keySet()
and entrySet()
of interface Map
that returns Sets
backed by Map
).
However, several implementations Set
use an implementation Map
backup to store their data (the elements of the keys Set
conversion in the underlying Map
, and the values of the underlying Map
are only fictitious objects). This is true for HashSet
and TreeSet
.
This is mentioned in the Javadoc :
public class HashSet
extends AbstractSet
implements Set, Cloneable, Serializable
This class implements the Set interface, backed by a hash table (actually an instance of HashMap ).
And TreeSet :
public class TreeSet extends AbstractSet implements
NavigableSet, Cloneable, Serializable
An implementation of NavigableSet based on a TreeMap .
Example:
public boolean More ...add(E e) {
return map.put(e, PRESENT)==null;
}
Here, PRESENT
is a static value fictitious object that must be kept in the reference map.
private static final Object PRESENT = new Object();
The Backing Map object is created when we invoke several construtors of HashSet
:
public More ...HashSet() {
map = new HashMap<E,Object>();
}
public More... HashSet (Colección c) {
map = new HashMap (Math.max ((int) (c.size () /. 75f) + 1, 16));
addAll (c);
}
public More... HashSet (int initialCapacity, float loadFactor) {
map = new HashMap (initialCapacity, loadFactor);
}
See javadocs for other implementations of sets supported by Map.