集合——HashMap

HashMap

  • 数组+链表+红黑树
  • key不能重复,但值可以,允许使用null值和null键
  • 如果添加相同的key,则会覆盖原来的key-value
  • 无序
  • 线程不安全

实现

public class test {
    public static void main(String[] args) {
        //创建HashMap对象
        /*
         *   public HashMap() {
               //初始化加载因子 0.75f
               this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
             }
        */
        HashMap map = new HashMap();
        /*  map.put(k,v);
            public V put(K key, V value) {
              return putVal(hash(key), key, value, false, true);
            }
        */
        map.put("",1);
        map.put(1,"");
        map.put(null,null);
        map.put(null,1);
        System.out.println(map);
    }
}
  • return putVal(hash(key), key, value, false, true);
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable 
{
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果node为一个空数组,调用resize()初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

//如果hash计算出的数组下标值为空,创建一个新的节点给当前下标
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//如果下标存在同一地址或相同内容的key时进入
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);
//如果链表长度>8,考虑将链表转为红黑树结构
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果下标存在同一地址或相同内容的key时,退出循环
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)
//覆盖同一已存在key的vlaue
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//如果size+1>length*0.75,则要对数组扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
}

  • resize();
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //当前数组的临界点值 假设为初始的12
        int oldThr = threshold;
        int newCap, newThr = 0;
        //如果当前数组长度大于0
        if (oldCap > 0) {
            //如果长度大于最大数
            if (oldCap >= MAXIMUM_CAPACITY) {
                //加载因子为int最大值
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //如果当前数组长度*2<最大值 and 数组长度>=默认数组长度16
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //加载因子 * 2
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            //如果加载因子>0,将初始容量设为阀值
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            //初识容量设为16,阀值设为12
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        //...省略代码块
        return newTab;
    }
  • treeifyBin(tab, hash);
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        //如果数组为空 或者 数组长度<64,先对数组进行扩容
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        //否则树化
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }
posted @ 2021-09-19 15:54  你们都不上班吗  阅读(39)  评论(0)    收藏  举报