Java源码分析 - HashMap 源码分析

HashMap 简介

HashMap 实现了Map接口,允许null key或者null value,与HashTable相似,但是HashTable 不允许空值并且是线程安全的。

HashMap get与put都可以在常数时间内执行,即为O(1)。

影响HashMap的性能有两个因素:Capacity 和 load factor, Capacity是hashtable的桶的数量,load factor 是在扩容之前桶可以装满的程度。当数量超过factor*Capacity 的时候,hashmap扩容为接近桶数量的二倍。

HashMap非线程安全,可以包装在自定义的线程安全的类中,或者使用Collections.synchronizedMap方法

Map m = Collections.synchronizedMap(new HashMap(...));

构造方法

HashMap 可实例化时指明 loadFactor,如果未指明设为默认值,如果指明了initialCapacity会计算出阈值threshold。
HashMap()
HashMap(int initialCapacity)
HashMap(int initialCapacity, float loadFactor)
HashMap(Map<? extends K, ? extends V> m)

tableSizeFor() 方法可以返回大于cap的最小的2的幂值。方法为把所有位的值置为1,然后把结果加1。
eg. cap = 10100
n = 10100 | 1010
n = 11110 | 111
n = 11111 | 11

n+1 = 100000

    /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

HashMap hash函数

高低位共同参与运算,使hashmap分布更加均匀,降低hash冲撞。

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

resize方法

resize 初始化table或者扩容,树化,链表化
resize 重新定义或者初始化参数,如果需要扩容,容量,阈值都扩大一倍(最大值范围内),将旧表的值转移到新表。遍历所有位置,如果该位置为不为空且只有一个值,将该值放置新表 hash&(新容量-1) 位。如果该位置已经树化,调用TreeNode.split方法,如果该位置已经链表化,使用 hash&旧容量 区分高低位,低位放置原处,高位放置于 旧容量+原下标处。

    final Node<K,V>[] resize() {
    	// oldTab 当前的桶
        Node<K,V>[] oldTab = table;
       //当前桶的个数,阈值,创建int新容量和新阈值
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        //如果当前容量大于0
        if (oldCap > 0) {
            // 当前容量超过最大容量,阈值设为最大,不再扩容
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 新容量*2后小于最大值,并且原容量大于等于初始值,新阈值等于原阈值*2
            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);
        }
        // 如果新阈值是0,表为空,初始化指定了容量和阈值或容量
        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) {
                    // 旧桶置为空,GC
                    oldTab[j] = null;
                    // 如果链表只有一个元素,更新至新桶,位置为 hash & (新容量-1)                    
                    if (e.next == null)
                    // 桶容量为2的幂数,相当于取模
                        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;
                            // 利用位运算,取得哈希值去模之后的值
                            // 如果为0,则为低位,下标不变
                            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;
    }

put 方法

put方法调用hash() 方法,高低位共同参与计算。

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<K,V> p; int n, i;
        // 如果现表为空,初始化
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 如果现表 (n-1)&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);
                        // 链表节点达到树化阈值,树化
                        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;
                }
            }
            // 如果找到需要覆盖的节点,如果onlyIfAbsent为false或者原值为空,覆盖
            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();
        // 空方法,LinkedHashMap重写
        afterNodeInsertion(evict);
        return null;
    }

get 方法

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 如果table非空,并且在 hash&(n-1) 处有值
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            // 如果首届点的key值等于传入的key值,返回首节点
            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;
    }

remove方法

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }
// matchValue 如果为 true, 当value值同时,移除节点
// movable 如果为 false, 不移除其他节点
    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            // node用于记录 是否有key值相同的值
            Node<K,V> node = null, e; K k; V v;
            // 如果 (n-1)&hash 位有值,赋值为p;key值同,则证明找到了key值相同的该位置节点。赋值为node。
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
           // 如果 key值不等,且p有子节点,证明已经链化或者树化
            else if ((e = p.next) != null) {
            // 如果 p已经树化,使用红黑树的遍历方式
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
             // 如果已经链化,循环遍历链表,如果找到 key 值相同的,赋值给node
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            // 如果找到了 node,并且如果 matchValue 值为 true时,value值相等。
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                // 如果已经树化,调用红黑树 removeTreeNode 方法
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                // 如果已经链化,且第一位为node,将指针指到 node.next
                // 或者没有链化,将该位赋值为 null (node.next)
                else if (node == p)
                    tab[index] = node.next;
                // 否则将p的下一位赋值为node下一位
                else
                    p.next = node.next;
                ++modCount;
                --size;
                // 定义一个callback
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值