美文网首页
HashMap源码阅读

HashMap源码阅读

作者: YphantomS4 | 来源:发表于2018-01-24 20:30 被阅读0次

定义

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable

可以看到HashMap是继承 AbstractMap实现了Map,Cloneable,Servializable接口的一个类。

Map

Map接口定义了我们日常工作中用map处理的常用函数

int size();
int size();
...
interface Entry<K,V> { ... } //定义了存储数据的接口
default V computeIfAbsent(K key,
          Function<? super K, ? extends V> mappingFunction) { ... }
default V computeIfPresent(K key,
          BiFunction<? super K, ? super V, ? extends V> remappingFunction) { ... }
default V compute(K key,
          BiFunction<? super K, ? super V, ? extends V> remappingFunction)
default V merge(K key, V value,
          BiFunction<? super V, ? super V, ? extends V> remappingFunction)

里边比较不常见的方法是几个compute方法,这是java8加入的函数式接口编程新特性,详情可以参见 http://colobu.com/2014/10/28/secrets-of-java-8-functional-interface/.这里举个例子来展示下:

public class Test {
  public static void main(String [] args) {
    Map<Integer, Integer> map = new HashMap<>();
    map.computeIfAbsent(1, Test::mul); // 将key * 2然后放入map {1=2}
    map.computeIfPresent(1, Test::add); // 将key + map.get(key)然后放入map {1=3}
    map.merge(1, 3, Test::add); // 将map.get(key) + 3 放入map {1=6}
    System.out.println(map);
  }

  public static int mul(int a) {
    return a * 2;
  }

  public static int add(int a, int b) {
    return a + b;
  }
}

AbstractMap

AbstractMap只是提供一个基础的实现,实现了Map.Entry。

public static class SimpleEntry<K,V>
    implements Entry<K,V>, java.io.Serializable { ... }
public static class SimpleImmutableEntry<K,V>
    implements Entry<K,V>, java.io.Serializable { ... }

HashMap

HashMap对Map.Entry实现如下:

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
}

我们常用的建立HashMap调用如下构造方法:

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted

这个构造方法只设置了负载因子,默认值为0.75,那么HashMap初始化是在什么地方完成的呢?

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

当我们第一次调用put方法的时候,会调用resize方法。

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

resize()方法在发现HashMap没有初始化capacitythreshold的时候,会将他们的值设置为初始值(DEFAULT_INITIAL_CAPACITY,DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY),所以初始capacity的值为16,threshold值为12。默认值的定义如下:

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

HashMap中的hash函数为(capacity-1)&hash(key),持续放入新的值,当存入的节点数超过threshold的时候,会再次触发resize()方法,此时会将capacitythreshold右移一位,将老的节点数组中的节点移动新的节点数组中,然后将老的数组元素显式设置为null。由于容量向右移动一位,那么hash的时候原来同一个桶中的数据会根据最高位不同被分到两个桶中,然后循环将原来的值分成两个链表,将表头分别赋值给新的桶就完成了数据的迁移。
如果一个桶中的节点数超过 TREEIFY_THRESHOLD (=8)时,会触发treeifyBin()treeifyBin()会将capacity大于MIN_TREEIFY_CAPACITY (=64)的HashMap中hash到同一个桶中的节点用红黑树来存储(Node -> TreeNode)。

相关文章

  • Java集合框架—HashMap—源码研读1

    前言: 本篇为HashMap源码研读系列第一篇,主要分析HashMap中put()方法的源码。阅读前需要对Hash...

  • Java集合-HashSet源码实现分析

    概要 阅读本文前,请先阅读笔者写的文章:Java集合-HashMap源码实现深入解析理解了HashMap,再来理解...

  • 源码阅读 - HashMap

    本文涉及到红黑树的部分参考二叉树 - 红黑树 0. HashMap是什么 一种增删改查操作(不考虑哈希冲突)能达到...

  • HashMap源码阅读

    HashMap概述 hashMap是在Java中经常使用的一个类,继承自AbstractMap类实现了map接口,...

  • HashMap源码阅读

    定义 可以看到HashMap是继承 AbstractMap实现了Map,Cloneable,Servializab...

  • HashMap源码阅读

    1. 什么是HashMap? 1.1 map的定义 首先你要知道什么是map,map就是用于存储键值对(

  • HashMap 源码阅读

    HashMap 源码阅读 之前读过一些类的源码,近来发现都忘了,再读一遍整理记录一下。这次读的是 JDK 11 的...

  • HashMap源码阅读

    本文基于JDK1.8 >读完本文预计需要25分钟(因有大量源代码,电脑屏观看体验较佳) 摘要 HashMap相信...

  • HashMap 源码阅读

    HashMap 在 java map 中的继承关系 底层存储结构: Node 类型数组image.png 存储数据...

  • 源码阅读——HashMap

    讲解之前,先测试下你对hashMap的理解 1:说说HashMap 底层数据结构是怎样的? 2:谈一下HashMa...

网友评论

      本文标题:HashMap源码阅读

      本文链接:https://www.haomeiwen.com/subject/waceaxtx.html