private transient HashMap<E,Object> map; // 维护了一个HashMap的变量
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object(); // 虚设的值
添加元素
/**
* Adds the specified element to this set if it is not already present.
* More formally, adds the specified element <tt>e</tt> to this set if
* this set contains no element <tt>e2</tt> such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns <tt>false</tt>.
*
* @param e element to be added to this set
* @return <tt>true</tt> if this set did not already contain the specified
* element
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null; // 将值作为key-value的key添加到map中,value为虚设的PRESENT。借助map的key不能重复来保证set中的值不重复
}
判断元素是否存在
/**
* Returns <tt>true</tt> if this set contains the specified element.
* More formally, returns <tt>true</tt> if and only if this set
* contains an element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this set is to be tested
* @return <tt>true</tt> if this set contains the specified element
*/
public boolean contains(Object o) {
return map.containsKey(o); // 添加到set中的元素都作为map的key,所以直接用map是否包含该key来判断
}