Reputation: 504
There is a method in the Collections class.
Set<E> Collections.newSetFromMap(<backing map>)
What does it mean by the backing map and the set backed by a map?
Upvotes: 8
Views: 5000
Reputation: 6614
I just made an example code for you
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
Set<String> set = Collections.newSetFromMap(map);
System.out.println(set);
for (int i = 0; i < 10; i++)
map.put("" + i, i % 2 == 0);
System.out.println(map);
System.out.println(set);
and the output
[]
{3=false, 2=true, 1=false, 0=true, 7=false, 6=true, 5=false, 4=true, 9=false, 8=true}
[3, 2, 1, 0, 7, 6, 5, 4, 9, 8]
Upvotes: 5
Reputation: 2176
Simply put, Collections.newSetFromMap uses the provided Map<E>
implementation to store the Set<E>
elements.
Upvotes: 4
Reputation: 102
The Set internally uses Map to store the values. Here the backing map refers to the set map which is internally used by the set. For more information. http://www.jusfortechies.com/java/core-java/inside-set.php
Upvotes: 0
Reputation: 30746
Perhaps it would be illuminating to look at the implementation:
private static class SetFromMap<E> extends AbstractSet<E>
implements Set<E>, Serializable
{
private final Map<E, Boolean> m; // The backing map
private transient Set<E> s; // Its keySet
SetFromMap(Map<E, Boolean> map) {
if (!map.isEmpty())
throw new IllegalArgumentException("Map is non-empty");
m = map;
s = map.keySet();
}
public void clear() { m.clear(); }
public int size() { return m.size(); }
public boolean isEmpty() { return m.isEmpty(); }
public boolean contains(Object o) { return m.containsKey(o); }
public boolean remove(Object o) { return m.remove(o) != null; }
public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }
public Iterator<E> iterator() { return s.iterator(); }
public Object[] toArray() { return s.toArray(); }
public <T> T[] toArray(T[] a) { return s.toArray(a); }
public String toString() { return s.toString(); }
public int hashCode() { return s.hashCode(); }
public boolean equals(Object o) { return o == this || s.equals(o); }
public boolean containsAll(Collection<?> c) {return s.containsAll(c);}
public boolean removeAll(Collection<?> c) {return s.removeAll(c);}
public boolean retainAll(Collection<?> c) {return s.retainAll(c);}
// addAll is the only inherited implementation
private static final long serialVersionUID = 2454657854757543876L;
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException
{
stream.defaultReadObject();
s = m.keySet();
}
}
Edit - added explanation:
The map that you provide is used as the m
field in this object.
When you add an element e
to the set, it adds an entry e -> true
to the map.
public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }
So this class turns your Map
into an object that behaves like a Set
by simply ignoring the values that things are mapped to, and just using the keys.
Upvotes: 8