1.HashSet介绍
HashSet基于Set接口的实现,内部存储数据是用的HashMap,其操作都是基于HashMap的
2.几个重要的参数
private transient HashMap<E,Object> map;//内部存储数据
private static final Object PRESENT = new Object();//构造一个空虚拟的对象
public HashSet() {
map = new HashMap<>();//默认使用HashMap的初始容量和加载因子16和0.75
}
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
3.主要看一下HashSet的add方法
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
HashMap.java
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)//根据key的hash找到在table中的位置index,取出该节点p
tab[i] = newNode(hash, key, value, null);//table中没有则直接添加新节点,直接执行最后的return null
else {//如果hash相等,也即是有冲突发生
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))//hash相等,并且key也相等,则取出p赋值给e,不走下面的else
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;//这里将虚拟对象重新赋值成虚拟对象PRESENT
afterNodeAccess(e);
return oldValue;//返回PRESENT,HashSet中map.put(e, PRESENT)==null返回false
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;//HashSet中没有相同的的元素时执行到这里
}
注意:在HashSet中是没有get方法的,要取出HashSet中的元素可以用迭代器遍历
4.contains(Object o)方法
public boolean contains(Object o) {
return map.containsKey(o);
}
HashMap.java
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;//找到了Object key
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);//有冲突,并且节点是红黑树,直接在树中查找
do {//否则,还是有冲突,并且节点是链表,则循环查找
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}