HashSet类是如何实现添加元素保证不重复的
[toc]
参考:!HashSet类是如何实现添加元素保证不重复的---哈希码的原理
总结
向HashSet中add()元素时,判断元素是否存在的依据,不仅要比较hash值,同时还要结合equles方法比较。
HashSet中的add()方法会使用HashMap的add()方法。
源码:
类中map和PARENT的定义:
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
//用来匹配Map中后面的对象的一个虚拟值
private static final Object PRESENT = new Object();
HashSet 类中的add()方法:
//boolean java.util.HashSet.add(E e)
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
map.put(e, PRESENT)是来自HashMap中的put方法
//java.util.HashMap.put(K key, V value)
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
hash()函数
//java.util.HashMap.put(K key, V value)
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//java.util.HashMap.put(K key, V value)
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)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
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;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}