hashMap 的实现原理

来源:互联网 发布:大掌柜软件使用教程 编辑:程序博客网 时间:2024/06/16 15:08

hashmap 的实现原理。(jdk 1.8)
参考资料:
http://tech.meituan.com/java-hashmap.html (写的很详细,强烈推荐,本文也是在这基础上添加自己的理解)

讲解下put 方法的流程,图片是盗用参考资料里面的图。
这里写图片描述

一些相关说明:
hashcode():返回该对象的哈希码值,在hashmap 中,存储和查找对象用(下面会说)。

一些相关字段:
链表上的值超过 TREEIFY_THRESHOLD = 8 ,就将转化为红黑树。
MAXIMUM_CAPACITY = 1 << 30; 最大的容量
DEFAULT_LOAD_FACTOR = 0.75f; 默认 负载因子。
DEFAULT_INITIAL_CAPACITY = 1 << 4; 默认 tab 大小 16
threshold = DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR ;用来存储map 中键值对的一个阈值。默认是 12。

node(存储数据用,简单写下):

        final int hash;        final K key;        V value;        Node<K,V> next;

计算key 的 hash 值:map 中的 key 的hash 值,是通过 hashcode 和 hashcode 右移16位,异或之后的结果(相同为 0,不同为 1)。之所以这样子操作,是为了让减少map的碰撞率。因为当 map 中 table 的长度很小的时候(默认是16)

    static final int hash(Object key) {        int h;        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);    }

将数据放到对应的table 中。(因为table 的长度 都是 2的倍数,所以 & 运算和 % 没区别)

tab[i = (n - 1) & hash]); // n 长度,hash 是你的key  的 哈希值。

整个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;        if ((tab = table) == null || (n = tab.length) == 0)            n = (tab = resize()).length; // 初始化,默认tab length是16,factor 是 0.75         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;    }

table 的扩容:

    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;                            // 通过 和 tab.length & 运算,来判断扩容之后的数据是放在原来的位置,还是移动到  原来位置+tab.length,的位置                            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;    }

希望有小伙伴能多多交流。

原创粉丝点击