Java HashMap源码解读

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_32197439/article/details/82286873

Java HashMap源码解读

  • 目前网上关于jdk hashmap源码解读的文章已经有很多,而写该博客的主要是为了记录自己对于源码学习过程,期间参考了许多其他优秀博客的理

分析思路

  • 先整体后细节
  • 先简单后复杂

实现结构

extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable 

数据结构

  • 数组+链表+红黑树
  • hashmap 底层的数组称为哈希桶,每个桶里放的是链表,当链表长度大于8会转变为红黑树,目的是为了提高插入与查询的效率
  • 由于底层是数组实现,当插入的元素达到一定数量是会进行扩容操作,变为原来的两倍
  • 我们可以将hashmap理解为了一个桶

进入正题

  • 有了桶这个概念后我们将对以下几个属性进行理解
    • capacity 桶的容量 这个桶能装多少东西
    • size 桶已经装了多少东西
    • loadFactory 负载因子 衡量桶是否应该扩容的标准 hashmap默认值0.75f,一般不去改
    • threshold capacity*loadFactory 当size>threhold时进行扩容,扩容是容量翻倍,所以原链表上的每个节点,现在可能存放在原来的下标,即low位, 或者扩容后的下标,即high位。 high位= low位+原哈希桶容量
  • 链表节点Node
    • 描述了链表的结构
// 单链表
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash; 节点的hash值
        final K key;  key值
        V value; 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() {
            // 由key和value的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;
        }
    }
  • 构造函数
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 初始容量 16

    static final int MAXIMUM_CAPACITY = 1 << 30;// 最大容量 2^30

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

    public HashMap(int initialCapacity) {// 自定义初始容量的构造函数,在初始化HashMap的时候,应该尽量指定其大小。尤其是当你已知map中存放的元素个数时
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public HashMap() {// 不带参数的构造函数
        this.loadFactor = DEFAULT_LOAD_FACTOR;
    }

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

    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;
    }
  • putAll()
    public void putAll(Map<? extends K, ? extends V> m) {
        putMapEntries(m, true);
    }
    // 将map的所有元素加入表中
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                // 重新计算阈值
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                // 扩容
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }
  • resize()扩容 划重点
final Node<K,V>[] resize() {
        // 当前hashTab
        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)
                // 2倍扩容
                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"})
        // 构建新的hash桶
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            // 遍历老的hash桶
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    // 原来的node置空 以便GC
                    oldTab[j] = null;
                    if (e.next == null)
                        // 位操作代替取模%,没有发生冲突
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
//如果发生过哈希碰撞,节点数小于8个。则要根据链表上每个节点的哈希值,依次放入新哈希桶对应下标位置。
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
// 扩容操作翻倍 原来的要么在index 要么index+oldLength
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
// 取模看是否小于oldCap ==0 小于 oldCap index
                            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
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
// onlyIfAbsent if true, don't change existing value 表示这个值是true 不会覆盖相同key-value
// boolean evict false表示初始时创建
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)
    // 没有发生冲突 构建新Node
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
// hash值相同 key相同 覆盖value
            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
                        // 链表长度大于8 转红黑树
                            treeifyBin(tab, hash);
                        break;
                    }
                 //如果找到了要覆盖的节点
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // 如果e不为空 找到要覆盖的节点
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
            // 覆盖并返回oldValue
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
// 空实现 用作linkedHashMap
                afterNodeAccess(e);
                return oldValue;
            }
        }
        // 更新修改次数++ 
        ++modCount;
        // 判断是否需要扩容
        if (++size > threshold)
            resize();
    //这是一个空实现的函数,用作LinkedHashMap重写使用。
        afterNodeInsertion(evict);
        return null;
    }
// 扰动函数 高位参与运算使得hash值更加均匀,减少hash碰撞概率
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
  • remove()
// 删除key-value对 返回value
public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

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;
        // 如果tab不为空 且根据hash找到节点有值
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
        // node为待删除节点
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
        // 删除节点引用赋值给node
                node = p;
            else if ((e = p.next) != null) {//否则循环遍历 找到待删除节点,赋值给node
                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);
                }
            }
            //如果有待删除节点node,  且 matchValue为false,或者值也相等
            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;
    }
  • get()
 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;
// 根据hash和key值找到node,找到返回value 否则 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<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;
    }
  • containsKey(key)
public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

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;
    }
  • containsValue()
 public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
        遍历hash桶 找到value 返回true
        if ((tab = table) != null && size > 0) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                        (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }
  • getOrDefault() 没有查到就返回默认值
 @Override
    public V getOrDefault(Object key, V defaultValue) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
    }

hashmap与其他类的对比

  • 与hashtable的对比
    • 1.HashTable的方法是同步的,在方法的前面都有synchronized来同步,HashMap未经同步,所以在多线程场合要手动同步
    • 2.HashTable不允许null值(key和value都不可以) ,HashMap允许null值(key和value都可以)。
    • 3.HashTable有一个contains(Object value)功能和containsValue(Object value)功能一样。
    • 4.HashTable使用Enumeration进行遍历,HashMap使用Iterator进行遍历。
    • 5.HashTable中hash数组默认大小是11,增加的方式是 old*2+1。HashMap中hash数组的默认大小是16,而且一定是2的指数。
    • 6.哈希值的使用不同,HashTable直接使用对象的hashCode,hashmap高低位参与运算
  • 与hashSet的对比
    • hashset底层是通过hashmap实现的
public HashSet() {
map = new HashMap<E,Object>();
}
  • 调用HashSet的add方法时,实际上是向HashMap中增加了一行(key-value对),该行的key就是向HashSet增加的那个对象,该行的value就是一个Object类型的常量
  • 与concurrentHashmap
    • 线程安全
      // 未完待续

猜你喜欢

转载自blog.csdn.net/sinat_32197439/article/details/82286873