JDK8 HashMap源码解析

  • Map的创建:HashMap()
  • 添加键值对:即put(K key, V value)方法
  • 删除对象:即remove(Object key)方法
  • 取单个对象:即get(Object key)方法
  • 判断对象是否存在:containsKey(Object key)

1.构造函数

    //默认容量为16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 

    //最大容量 2的30次方
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //默认的加载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //哈希桶,存放链表。 长度是2的N次方,或者初始化时为0.
    transient Node[] table;

    //加载因子,用于计算哈希表元素数量的阈值。  threshold = 哈希桶.length * loadFactor;
    final float loadFactor;

    //哈希表内元素数量的阈值,当哈希表内元素数量超过阈值时,会发生扩容resize()。
    int threshold;

    //新建一个哈希表,同时将另一个map m 里的所有元素加入表中
    public HashMap(Map m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

    public HashMap() {
        //默认构造函数,赋值加载因子为默认的0.75f
        this.loadFactor = DEFAULT_LOAD_FACTOR; 
    }

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

    //同时指定初始化容量 以及 加载因子, 用的很少,一般不会修改loadFactor
    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);
    }
    //返回大于等于cap的最小2次方数
    static final int tableSizeFor(int cap) {
        //经过下面的 或 和位移 运算, n最终各位都是1。
       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;
    }

2.扩容函数

    final Node[] resize() {
        Node[] oldTab = table;//当前数组
        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;
            }
            //当前数组容量大于等于16切扩容后小于最大容量限制,扩容阈值增加一倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; 
        }
        //如果当前表是空的,但是有阈值。代表是初始化时指定了容量、阈值的情况HashMap(int,float)、HashMap(int)
        else if (oldThr > 0)
            newCap = oldThr;//旧阈值成为新容量
        else {//未指定容量和阈值HashMap(),默认赋值               
            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[] newTab = (Node[])new Node[newCap];
        //更新数组引用    
        table = newTab;
        //复制链表数据
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;//置空以便GC
                    //如果当前链表中就一个元素,(没有发生哈希碰撞)
                    if (e.next == null)
                        //直接将这个元素放置在新的哈希桶里。
                        newTab[e.hash & (newCap - 1)] = e;
                    //如果发生过哈希碰撞 ,而且是节点数超过8个,转化成了红黑树    
                    else if (e instanceof TreeNode)
                        ((TreeNode)e).split(this, newTab, j, oldCap);
                    //如果发生过哈希碰撞,节点数小于8个。则要根据链表上每个节点的哈希值,依次放入新哈希桶对应下标位置。    
                    else {
                        Node loHead = null, loTail = null;
                        Node hiHead = null, hiTail = null;
                        Node 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;
    }

3.put(K key, V value)

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

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

    //如果onlyIfAbsent为true则不会覆盖相同key的值,evict为false表示初始化
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node[] tab; Node p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)//当前哈希表为空,直接扩容
            n = (tab = resize()).length;
        //如果当前index的节点是空的,表示没有发生哈希碰撞。直接构建一个新节点Node,挂载在index处即可。
        //index是利用哈希值&哈希桶的长度-1,替代模运算    
        if ((p = tab[i = (n - 1) & hash]) == null)//p获取tab链表节点
            tab[i] = newNode(hash, key, value, null);
        else {//发生哈希冲突
            Node e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))//哈希值相等,key也相等,覆盖value操作
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode)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;
    }    

4.remove(Object key)

    public V remove(Object key) {
        Node e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

    //如果参数matchValue是true,则必须key 、value都相等才删除。 
    //如果movable参数是false,在删除节点时,不移动其他节点
    final Node removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        // p 是待删除节点的前置节点
        Node[] tab; Node p; int n, index;
        //如果哈希表不为空,则根据hash值算出的index下 有节点的话。
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            //node是待删除节点
            Node node = null, e; K k; V v;
            //如果链表头的就是需要删除的节点
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;//将待删除节点引用赋给node
            else if ((e = p.next) != null) {//否则循环遍历 找到待删除节点,赋值给node
                if (p instanceof TreeNode)
                    node = ((TreeNode)p).getTreeNode(hash, key);
                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为false,或者值也相等
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode)node).removeTreeNode(this, tab, movable);
                else if (node == p)//如果node ==  p,说明是链表头是待删除节点
                    tab[index] = node.next;
                else//否则待删除节点在表中间
                    p.next = node.next;
                ++modCount;//修改modCount
                --size;//修改size
                afterNodeRemoval(node);//LinkedHashMap回调函数
                return node;
            }
        }
        return null;
    }

    void afterNodeRemoval(Node p) { }

5.get(Object key)

    public V get(Object key) {
        Node e;
        //传入扰动后的哈希值 和 key 找到目标节点Node
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    //传入扰动后的哈希值 和 key 找到目标节点Node
    final Node getNode(int hash, Object key) {
        Node[] tab; Node first, e; int n; K k;
        //查找过程和删除基本差不多, 找到返回节点,否则返回null
        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)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;
    }

6.containsKey(Object key)

    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

你可能感兴趣的:(java)