HashMap原理浅谈

488 阅读4分钟

HashMap原理浅谈

以下全部代码都来自jdk1.8源码HashMap.java

源码阅读一

HashMap其中部分源码

// 默认初始化数组大小
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 转化成红黑树的链表大小的阈值
static final int TREEIFY_THRESHOLD = 8;
// 取消红黑树结构的最小阈值
static final int UNTREEIFY_THRESHOLD = 6;
// 为了避免调整大小和树化阈值之间的冲突,阈值不能高于4 * TREEIFY_THRESHOLD
static final int MIN_TREEIFY_CAPACITY = 64;
...
public HashMap(int initialCapacity, float loadFactor) {
     if (initialCapacity < 0)
         throw new IllegalArgumentException("Illegal initial capacity: " +
                                            initialCapacity);
     if (initialCapacity > MAXIMUM_CAPACITY)
         initialCapacity = MAXIMUM_CAPACITY;
     if (loadFactor <= 0 || Float.isNaN(loadFactor))
         throw new IllegalArgumentException("Illegal load factor: " +
                                            loadFactor);
     this.loadFactor = loadFactor;
     this.threshold = tableSizeFor(initialCapacity);
 }

 public HashMap(int initialCapacity) {
     this(initialCapacity, DEFAULT_LOAD_FACTOR);
 }

 public HashMap() {
     this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
 }

 public HashMap(Map<? extends K, ? extends V> m) {
     this.loadFactor = DEFAULT_LOAD_FACTOR;
     putMapEntries(m, false);
 }

从HashMap的构造函数来看,初始化数组大小和负载因子是可以指定的

源码阅读二

HashMap底层究竟是什么构成的

// 节点数组
transient Node<K,V>[] table;
...
// 节点结构,单链表
static class Node<K,V> implements Map.Entry<K,V> {
     final int hash;
     final K key;
     V value;
     Node<K,V> next;

     Node(int hash, K key, V value, Node<K,V> next) {
         this.hash = hash;
         this.key = key;
         this.value = value;
         this.next = next;
     }
	 ...
 }
 ...
 // 树节点
 static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    TreeNode<K,V> parent;  // red-black tree links
    TreeNode<K,V> left;
    TreeNode<K,V> right;
    TreeNode<K,V> prev;    // needed to unlink next upon deletion
    boolean red;
    TreeNode(int hash, K key, V val, Node<K,V> next) {
        super(hash, key, val, next);
    }
    ...
}

从代码可以看出,底层是由数组+链表+树构成

阅读源码三

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

/**
 * Implements Map.put and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */
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);
        // 如果经过hash的索引,添加一个新的节点
    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);
                    // 如果链表的数量达到了8,就转化成树结构
                    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
        	// 存在key,更新value
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
        // 扩容
    afterNodeInsertion(evict);
    return null;
}

put过程分析:

  1. 判断节点数组的长度
  2. 如果没有哈希冲突则添加第一个节点,如果哈希冲突则链接节点,如果链表长度超过8,则转化成树;由源码可知,哈希公式:index = HashCode(Key) & (Length - 1)
  3. 如果已经存在key,则替换旧的value

阅读源码四

public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

/**
 * Implements Map.get and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @return the node, or null if none
 */
final Node<K,V> getNode(int hash, Object key) {
    Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (first = tab[(n - 1) & hash]) != null) {
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        if ((e = first.next) != null) {
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            do {
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    return null;
}

get过程分析:

  1. 由key计算出哈希值
  2. 每次都要检查第一个节点,判断是链表节点还是树节点
  3. 如果是链表则链表寻找,如果是树则树寻找

阅读源码五

final Node<K,V>[] resize() {
     Node<K,V>[] oldTab = table;
     int oldCap = (oldTab == null) ? 0 : oldTab.length;
     int oldThr = threshold;
     int newCap, newThr = 0;
     if (oldCap > 0) {
     	 // 判断有没有超过最大值,如果没有,返回原数组
         if (oldCap >= MAXIMUM_CAPACITY) {
             threshold = Integer.MAX_VALUE;
             return oldTab;
         }
         else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                  oldCap >= DEFAULT_INITIAL_CAPACITY)
             newThr = oldThr << 1; // double threshold
     }
     else if (oldThr > 0) // initial capacity was placed in threshold
         newCap = oldThr;
     else {               // zero initial threshold signifies using defaults
         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;
     // 更新新的阈值
     if (oldTab != null) {
     	 // 将旧的数组的数据,按照规则迁移到新的数组上
         for (int j = 0; j < oldCap; ++j) {
             Node<K,V> e;
             if ((e = oldTab[j]) != null) {
                 oldTab[j] = null;
                 if (e.next == null)
                     newTab[e.hash & (newCap - 1)] = e;
                 else if (e instanceof TreeNode)
                     ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                 else { // preserve order
                     Node<K,V> loHead = null, loTail = null;
                     Node<K,V> hiHead = null, hiTail = null;
                     Node<K,V> next;
                     do {
                         next = e.next;
                         if ((e.hash & oldCap) == 0) {
                             if (loTail == null)
                                 loHead = e;
                             else
                                 loTail.next = e;
                             loTail = e;
                         }
                         else {
                             if (hiTail == null)
                                 hiHead = e;
                             else
                                 hiTail.next = e;
                             hiTail = e;
                         }
                     } while ((e = next) != null);
                     if (loTail != null) {
                         loTail.next = null;
                         newTab[j] = loHead;
                     }
                     if (hiTail != null) {
                         hiTail.next = null;
                         newTab[j + oldCap] = hiHead;
                     }
                 }
             }
         }
     }
     return newTab;
 }

扩容过程分析:

  1. 判断有没有超过最大值,如果没有,返回原数组,有则进行扩容
  2. 计算新的扩容量大小,newCap = oldCap << 1,扩大一倍
  3. 创建新的数组
  4. 将旧的数组的数据,按照规则迁移到新的数组上
  5. 返回新数组

图解过程

put过程

初始一个新的数组 在这里插入图片描述 put(k1, v1) put(k2, v2) put(k3, v3) k1和k2没有哈希冲突,k1和k3有哈希冲突 在这里插入图片描述

get过程

get(k2),计算出k2的哈希值,根据索引寻找,进行key值判断 在这里插入图片描述 get(k3),计算出k3的哈希值,根据索引寻找,进行key值判断 在这里插入图片描述

扩容过程

根据HashMap.Size >= Capacity * LoadFactor公式,达到了扩容条件,6>=8*0.75 在这里插入图片描述 创建一个新的数组,old<<1的大小,根据规则重新赋值 在这里插入图片描述

多线程问题

在这里插入图片描述

总结

  1. HashMap是一个用于存储Key-Value键值对的集合
  2. 底层由数组、链表、红黑树组成
  3. 初始容量为8,负载因子时0.75
  4. 线程不安全,可能出现链表循环

ps:能力有限,如有错误,请大家积极指出,谢谢!
关注CSDN