hashMap源码解析

源码来自jdk:1.8,和其他jdk版本可能有少许差异。

一.hashMap的实现原理

    hashMap底层是一个有Node组成的数组,每个Node都有一个key,一个value,一个通过对key的hashcode得到的hash值,和一个next指针。可以简单理解为一个数组,数组里每个元素存的是链表,链表过长就转化为红黑树。

/**
 *可以看到这个数组是被transient修饰,禁止被序列化,因为table数组是随时变化,
 *所以没必要序列化,序列化只会浪费存储空间,可以看到hashMap源码中很多属性都加了transient。
 */
transient Node<K,V>[] table; 
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash; //通过key的hashcode进行hash运算得到的hash值
        final K key; //键
        V value; //值
        Node<K,V> next; //指向下一个Node的指针

        Node(int hash, K key, V value, Node<K,V> next) { //构造函数
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }
}

1.当向hashMap中存储元素时,首先通过key的hashcode值计算出该元素的hash值,通过hash值来决定该元素存储在底层数组的哪个位置,当出现多个hash值时即hash冲突时,hashMap的解决方案是拉链法,在当前数组中元素的位置形成一个链表,新加入元素的放在链头,最先加入元素的放在链尾。

/**
     * 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);
        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;
    }

2.当从hashMap中取元素时,首先通过key的hashcode计算该元素的hash值,通过hash值找到该元素在数组的位置,如果该位置有多个元素,即形成了链表,则遍历链表,通过equals()方法诸个比较,找出元素。

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

3.

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

  /**
     * Implements Map.remove and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to match if matchValue, else ignored
     * @param matchValue if true only remove if value is equal
     * @param movable if false do not move other nodes while removing
     * @return the node, or null if none
     */
    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<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)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);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

4.当hash冲突很多,链表过长时,查询操作效率很低,这时候链表会转化成红黑树。

5.jdk1.8引入的红黑树,当链表长度为8时转化为红黑树,当红黑树长度为6时,转化为链表。

  5-1.为什么:在平均查找的时间效率上,红黑树是log(n),所以有8个元素时为log(8)=3;链表是n/2,长度为8时,平均时间为8/2=4;小于6链表平均时间少,大于8红黑树平均时间少,至于为什么会间隔一个7呢,那是因为链表和红黑树之间的转化也需要一定的时间成本,频繁转化会浪费很多时间,所以预留了一个7。

    static final int TREEIFY_THRESHOLD = 8;

    static final int UNTREEIFY_THRESHOLD = 6;

附:hash冲突的四种解决方法:https://blog.csdn.net/qq_27093465/article/details/52269862

一些重要属性:


    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;

    static final int MIN_TREEIFY_CAPACITY = 64;

  

 

预留。。。

 

二.什么是红黑树

平衡二叉搜索树(AVL树):一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。二叉查找树退化成链表的问题,把插入,查找,删除的时间复杂度最好情况和最坏情况都维持在O(logN)。但是频繁旋转会使插入和删除牺牲掉O(logN)左右的时间,不过相对二叉查找树来说,时间上稳定了很多。

https://www.cnblogs.com/zhangbaochong/p/5164994.html

红黑树:红黑树是自平衡二叉查找树的一种,包含以下特性。

    1. 节点是红色或黑色。

    2. 根节点是黑色。

    3.每个叶节点(NIL节点,空节点)是黑色的。

    4.每个红色节点的两个子节点都是黑色。(从每个叶子到根的所有路径上不能有两个连续的红色节点)

   5.从任一节点到其每个叶子的所有路径都包含相同数目的黑色节点。

图:https://www.cnblogs.com/skywang12345/p/3245399.html

hashMap中的红黑树:

    /**
     * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
     * extends Node) so can be used as extension of either regular or
     * linked node.
     */
    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // 红黑树的父节点
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // 删除需要取消的节点
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

        /**
         * Returns root of tree containing this node.
         */
        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }

它是继承于LinkedHashMap.Entry<K,V>的,从这里也可以看到LinkedHashMap底层是一个链表

    /**
     * HashMap.Node subclass for normal LinkedHashMap entries.
     */
    static class Entry<K,V> extends HashMap.Node<K,V> {
        Entry<K,V> before, after;
        Entry(int hash, K key, V value, Node<K,V> next) {
            super(hash, key, value, next);
        }
    }

hashMap是一种牺牲空间换取查找等操作时间的设计,所以空间转化率特别低,在面向对象的思想中不要滥用。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值