HashMap源码分析

我所使用的JDK版本时1.8.0_144。

HashMap是我们常用的一个数据结构,以键值对的形式进行操作。

源码分析如下:

//默认初始容量,必须为2的指数倍,原因在HashMap的put方法由讲解
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

//默认最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;

//默认加载因子, 指哈希表可以达到多满的尺度
static final float DEFAULT_LOAD_FACTOR = 0.75f;

//实际使用的哈希表
transient Node<K,V>[] table;

//HashMap大小, 即HashMap存储的键值对数量
transient int size;
 
//键值对的阈值, 用于判断是否需要扩增哈希表容量
int threshold;

//加载因子
final float loadFactor;
 
//修改次数, 用于fail-fast机制
transient int modCount;

哈希表的类结构如下,结构就是常见的链表结构,其中有属性:hash值,key键值,value值,next链表下一个值的对象:

 /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    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;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

HashMap构造函数如下,所有构造函数都会直接或间接实现下面这个主要构造函数的功能:

public HashMap(int initialCapacity, float loadFactor) {
     //HashMap的初始容量判空
     if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +initialCapacity);
        //HashMap的初始容量不可超过最大容量
     if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
     //加载因子,默认为0.75f
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        //初始化加载因子
     this.loadFactor = loadFactor;
        //初始化阈值
     this.threshold = tableSizeFor(initialCapacity);
    }

HashMap的hash算法和tableSizeFor算法详细讲解:https://blog.csdn.net/fan2012huan/article/details/51097331

HashMap的resize算法详细讲解: https://www.cnblogs.com/huangwentian/p/6928304.html

并发场景下HashMap死循环导致CPU100%的问题:http://www.cnblogs.com/kxdblog/p/4323892.html

 

HashMap存入方法,存入方法中有一段根据hash值获取下标的代码(用蓝色标志),说明了HashMap存储长度用2的指数倍原因:HashMap节点存储在Hash表下标值是由当前节点Hash值&HashMap长度-1,由于2的二进制为10,2的倍数的二进制为10....0,减一后01....1,可以利用更多的空间。因为如果n-1的二进制中任何位存在0值时,该位的1值就不能被存储利用到。

public V put(K key, V value) {   
    //调用存储函数      
    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变量
Node<K,V> p;

     int n, i;

     //初始化tab为当前哈希表,并且判空,如果当前哈希表还为空,则重新分配
if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length;

     //如果当前根据哈希值与表长度算出的该下标的表中Node为空,则创建Node节点,并存入哈希表中该下标
if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else {//否则,则是该Node的值不为空 //存储该下标的哈希值
Node
<K,V> e;
       //键值
       K k;

       //如果Node的hash值与存入的hash相同,则将当前表中Node变量赋值为e
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode)//如果Node值类型为TreeNode
          e
= ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else {//否则,循环查询出hash值和key值相同的节点并存储到e变量中 for (int binCount = 0; ; ++binCount) {
            //从Node值的next开始查询,如果为空,则将创建Node节点,并连接到Node的next节点上
            if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; }
            //如果存入成功,则e的hash值应该与hash相同
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e;  //循环遍历p的next,p = e即为p=p.next } }
        //如果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)  //如果表中数据个数+1,如果表中数据个数大于阈值,则重新分配表 resize(); afterNodeInsertion(evict); return null; }

 取数据(与存数据类似):

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

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;
    }

 

  

  

  

 

posted @ 2018-02-06 13:19  浩天817  阅读(198)  评论(0编辑  收藏  举报