HashMap 源码学习一

HashMap是我们常用的数据结构之一,之前我并没有仔细了解过它的底层原理,现在就来分析一下它的源码。

HashMap 在 java.util 下,继承了 AbstractMap

下面是 一些常量定义:

    // 默认初始化容量必须是2的倍数
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    
    // 最大容量,被用于任何一个带参数的构造器,必须是2的倍数 且小于 2^30
    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;

 HashMap 本质是Node 数组,Node 对象数据结构:hash, key, value, next

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V 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() {
            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;
        }
    }

HashMap 无参数构造方法,这里 默认初始大小是 16 ,加载因子是 0.75

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

带有初始容量的构造方法

public HashMap(int initialCapacity) {
        this(initialCapacity, 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);//把初始容量变成2的倍数
    }

下来再看看 put 操作

链表数据 put 操作源码如下:

    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;//如果table为null,初始化table
        if ((p = tab[i = (n - 1) & hash]) == null)// 根据hash值计算索引下标
            tab[i] = newNode(hash, key, value, null);// 如果索引对应的内容为null,直接创建
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;// 如果tab[i] 的首个元素和目标key一样,则直接赋值,后续覆盖value值
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//如果tab[i]是树节点直接跳转树节点的put的方法
            else {
                // 遍历tab[i] 下所有元素
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);//遍历结束不存在key,直接创建
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);//如果长度大于 8, 树化 tab 
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;//存在key值,直接赋值,后续覆盖value值
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;// 如果键值存在,替换value值
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();//扩容
        afterNodeInsertion(evict);
        return null;
    }

链表树化的方法

final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();// tab的大小 小于最小树化阖值,不进行树化,直接扩容
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);// 新建TreeNode,内容为tab[i]
                if (tl == null)// 树头节点
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);// 桶中第一个节点变成p
            if ((tab[index] = hd) != null)
                hd.treeify(tab);// 形成从该节点链接的节点的树
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_41452576/article/details/88105234