本文中涉及
HashMap
的知识参考HashMap源码阅读
0. HashSet是什么
- 实现
Set
接口,所以元素不重复,最多一个null
元素 - 不保证元素的存储顺序
1. 实现的本质
HashSet
是通过HashMap
来存储元素的,也是通过它来保证Key
的唯一性
在这个HashMap
中要存储的元素作为Key
,PRESENT
作为Value
来进行存储
private transient HashMap map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
2. 主要api解析
2.1 构造函数
在构造函数中初始化HashMap
,其中的capacity
和loadFactor
也是指定HashMap
的capacity
和loadFactor
。
public HashSet()
public HashSet(int initialCapacity)
public HashSet(int initialCapacity, float loadFactor)
public HashSet(Collection extends E> c)
2.2 add方法
往map
中存入一个元素,key
是需要存储的元素,value
是PRESENT
,由于HashMap
中key
是唯一的,所以Set
中的元素就是唯一的,不能重复
/**
* 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.
*
* @param e element to be added to this set
* @return true if this set did not already contain the specified
* element
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
2.3 remove方法
同样的,remove
方法也是从map
中删除元素
/**
* Removes the specified element from this set if it is present.
* More formally, removes an element e such that
* (o==null ? e==null : o.equals(e)),
* if this set contains such an element. Returns true if
* this set contained the element (or equivalently, if this set
* changed as a result of the call). (This set will not contain the
* element once the call returns.)
*
* @param o object to be removed from this set, if present
* @return true if the set contained the specified element
*/
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
2.4 遍历
遍历是遍历map
的keySet
/**
* Returns an iterator over the elements in this set. The elements
* are returned in no particular order.
*
* @return an Iterator over the elements in this set
* @see ConcurrentModificationException
*/
public Iterator iterator() {
return map.keySet().iterator();
}
3. 参考
- HashSet源码build 1.8.0_121-b13版本