In Java, HashSet uses HashMap to finish: add, get, iterator etc. The HashMap also can help an element inside HashSet is unique.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package tv.blackarrow; import java.util.AbstractSet; import java.util.HashMap; import java.util.Iterator; import java.util.Set; public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable { static final long serialVersionUID = -5024744406713321676L; private transient HashMap<E, Object> map; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(); public HashSet() { map = new HashMap<E,Object>(); } /** Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false. Parameters: e element to be added to this set Returns: true if this set did not already contain the specified element */ public boolean add(E e) { return map.put(e, PRESENT)==null; } public boolean remove(Object o) { return map.remove(o)==PRESENT; } @Override public Iterator<E> iterator() { return map.keySet().iterator(); } @Override public int size() { return map.keySet().size(); } public boolean contains(Object o) { return map.containsKey(o); } } |