Hashmap底层是(数组 + 链表 + 红黑树)
Hashset的添加机制 (难点)维护的是 数组+链表+红黑树
1.Hashset的底层是Hashmap
2.添加一个元素时, 先得到hash值 --会转成-->索引值(根据索引值查table表)
3.找到存储数据表table,看这个索引位置是否已经存放元素
4.如果没有,直接加入
5.如果有,就调用equals比较 ,如果相同,就放弃添加,如果不相同,则添加到最后
6.如果一个链表的元素长度超过了8,注意这里首先会对数据表进行扩容,两倍扩 MIN_TREEIFY 如果同时 存储表table表也大于64,就会将链表进行树化,会将链表转换成红黑树
1首先执行构造器
2.执行一个add方法
public boolean add(E e) {
return map.put(e, PRESENT)==null;
3.执行put方法 该方法会执行 hash方法 h>>>16为了避免碰撞
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
这里的三个值基本对应上文的添加顺序 hash(key)便是我们查表的值,key是我们添加的元素
4.执行put
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
这里的table 就是hashmap的一个属性 里面存放node Node数组
如果当前table等于空 或者大小等于0
就进行第一次扩容
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;
}
(初次追溯源码,哪里不对欢迎各位大佬批评指正)