HashSet集合的特点:
由于是Set集合,所以不包含重复元素
当用add添加元素时,如果多次添加相同的元素,集合里也只会存在一个,因为只会插入一次
源码添加注释如下:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
//计算对象的哈希值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//此处的形参key就是要插入的元素e
public V put(K key, V value) {
//hash(key)就是对象的哈希值
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)
tab[i] = newNode(hash, key, value, null);
//该位置有元素
else {
Node<K,V> e; K k;
/*判断该位置的元素和要插入元素的哈希值
如果哈希值不同,就直接向下进行,把元素添加到集合
如果哈希值相同,会调用对象的equals()方法比较
如果返回false,会继续向下执行,把元素插入到集合
如果返回true,说明元素重复,不存储
*/
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;
}
很清晰的可以看到,调用add()方法后,add()方法会调用put(),ptu()会调用putVal(),并且putVal将对象的哈希值作为第一个参数,对象作为第二个参数传递。
可以总结出HashMap添加集合的过程:
其实HashSet的底层是数组加链表实现的,通过hashcode的值计算出存储位置(比如取余求位置),这个位置就是对应的数组下标,如果该位置有元素了并且判断该位置的所有元素的哈希值和内容都与当前对象不同,那就当前对象接在这个位置存在的链表上,就像邻接表一样。