什么是HashMap

hashMap 是一个用于存储KEY-VALUE键值对的集合,每一个键值对也叫作Entry.这些个键值对(Entry)分散存储在一个数组中.

HashMap 的初始值大小为 16

HashMap中我们最常用到的两个方法: GET PUT

PUT方法的原理

首先 调用PUT方法时 都发生了什么?

  1. hash(key) 使用该hash函数来确定呢Entry的插入位置

    首先 HashMap的长度是有限的

    那么 当插入的Entry越来越多时,使用hash(key)函数计算出来的hash值就必定会存在相同的情况

  2. 对于相同的hash值 该怎么办? (hash冲突) => 链表

    HashMap 数组的每一个元素不止是一个Entry对象,也是一个链表的头节点.每一个Entry对象通过Next指针指向它的下一个Entry节点.当新来的Entry映射到冲突的数组位置时,只需要插入到对应的链表即可.

    **注意: **新来的Entry节点插入链表时,使用的是"头插法",即最新的元素放在链表的头部. 因为HashMap的发明者认为,后插入的Entry被查找的可能性更大

//以下部分为 hashMap中的源码
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
}
//putVal 方法
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;
    }