import java.util.Collection; import java.util.Map; import java.util.HashMap; import java.util.Iterator; public class GettableHashSet implements GettableSet { private Map map; public GettableHashSet() { this(16); } public GettableHashSet(Collection coll) { this(coll.size()); addAll(coll); } public GettableHashSet(int initialCapacity) { this(initialCapacity, 0.75f); } public GettableHashSet(int initialCapacity, float loadFactor) { map = new HashMap(initialCapacity, loadFactor); } public E get(E obj) { return map.get(obj); } public int size() { return map.keySet().size(); } public boolean isEmpty() { return map.isEmpty(); } public void clear() { map.clear(); } /** Note that calling this will replace any equal object currently in the set. */ public boolean add(E obj) { if (obj == null) throw new NullPointerException("null elements not supported"); // ban null to make computation of the return value a bit easier return map.put(obj, obj) == null; } // if you don't want replacement, either use this, or replace the normal add() with it public boolean addWithoutReplacing(E obj) { if (obj == null) throw new NullPointerException("null elements not supported"); // ban null to make computation of the return value a bit easier if (!map.containsKey(obj)) { map.put(obj, obj); return true; } else { return false; } } public boolean addAll(Collection coll) { boolean changed = false; for (E obj: coll) { changed = changed | add(obj); } return changed; } public boolean remove(Object obj) { return map.keySet().remove(obj); } public boolean removeAll(Collection coll) { return map.keySet().removeAll(coll); } public boolean retainAll(Collection coll) { return map.keySet().retainAll(coll); } public boolean contains(Object obj) { return map.containsKey(obj); } public boolean containsAll(Collection coll) { return map.keySet().containsAll(coll); } public T[] toArray(T[] arr) { return map.keySet().toArray(arr); } public Object[] toArray() { return map.keySet().toArray(); } public Iterator iterator() { return map.keySet().iterator(); } }