阅读 360

说说HashMap的实现原理

本文关于HashMap的底层实现若无特殊说明都是基于JDK1.8。

HashMap的底层数据结构是数组+链表(红黑树),它是基于hash算法实现的,通过put(key, value) 和 get(key) 方法存储和获取对象。

我们一般是这么使用HashMap的

Map<String, Object> map = new HashMap<>();
map.put("a", "first");
复制代码

当调用HashMap的无参构造方法时,HashMap的底层数组是没有初始化的。

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
复制代码

无参构造方法中只是对加载因子loadFactor初始化为默认值0.75,并没有对Node<K,V>[] table数组初始化。 (可以思考下HashMap中的加载因子为什么是0.75?)

put(key, value)方法存储元素

当我们第一次调用put(key, value) 方法时,key-value在HashMap内部的数组和链表中是如何存储的呢? put方法内部首先根据key计算hash值,hash函数是如何计算的呢?是直接返回key的hashCode吗,当然不是啦! HashMap中的hash算法:

/**
 * Computes key.hashCode() and spreads (XORs) higher bits of hash
 * to lower.  Because the table uses power-of-two masking, sets of
 * hashes that vary only in bits above the current mask will
 * always collide. (Among known examples are sets of Float keys
 * holding consecutive whole numbers in small tables.)  So we
 * apply a transform that spreads the impact of higher bits
 * downward. There is a tradeoff between speed, utility, and
 * quality of bit-spreading. Because many common sets of hashes
 * are already reasonably distributed (so don't benefit from
 * spreading), and because we use trees to handle large sets of
 * collisions in bins, we just XOR some shifted bits in the
 * cheapest possible way to reduce systematic lossage, as well as
 * to incorporate impact of the highest bits that would otherwise
 * never be used in index calculations because of table bounds.
 */
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
复制代码

key的hash值已经知道了,那么计算 hash & (table.length - 1) 结果就是key的hash值在数组table中的位置bucket。 等等,数组table还没有初始化呢,那么在计算bucket之前应该先将table[]数组进行初始化, 既然要初始化一个数组,那么数组的长度应该是多少呢?

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

默认的初始容量16,数组创建方式如下

newCap = DEFAULT_INITIAL_CAPACITY;
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
复制代码

Node[] 数组就这么被创建好了,是不是很简单(具体看源码中的resize()方法)。

数组创建好了,key在数组中对应的位置bucket也找到了,那么现在就该将key-value放入数组中了,该如何放入呢? 数组的类型为Node,那么需要将key-value封装成数组的元素类型Node。

/**
 * Basic hash bin node, used for most entries.  (See below for
 * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
 */
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;
    }
    // 省略其他部分代码
}
复制代码

Node类中包含4个属性,K key、V value、int hash、Node<K,V> next。 key、value就是我们要放入HashMap中的数据,hash就是我们上面计算出来的key的hash值,这个Node类型的next是干嘛的呢? 还记得HashMap底层的数据结构吗?数组 + 链表,next这个地方就是链表的实现。next指向与key的hash值相同的新Node。

根据key在数组中对应的位置bucket,获取bucket位置上的元素,如果该位置上没有元素,则直接将key-value封装成的Node放入数组中

tab = table
tab[i] = newNode(hash, key, value, null);
复制代码

如果该位置上有元素,则比较key的值是否相等,有两种情况:

1、如果key的值相等,则要更新key对应的vaule,将新的value覆盖旧的value;

2、如果key的值不相等,则说明发生了hash冲突。也就是说不同的key计算出的hash值相等,说明它们在table[]中在同一个位置, 这个时候就需要使用链表了,遍历链表,比较key值是否相等,直到链表的最后一个节点,若未找到则将新的元素插入到链表的尾部(尾插法)。

JDK1.8中put方法源码

/**
 * Associates the specified value with the specified key in this map.
 * If the map previously contained a mapping for the key, the old
 * value is replaced.
 *
 * @param key key with which the specified value is to be associated
 * @param value value to be associated with the specified key
 * @return the previous value associated with <tt>key</tt>, or
 *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
 *         (A <tt>null</tt> return can also indicate that the map
 *         previously associated <tt>null</tt> with <tt>key</tt>.)
 */
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

/**
 * 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)
        // 初始化table
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        // 目标位置上没有元素,直接将key-value封装成的Node放入数组
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        // 目标位置上有元素,则比较key值是否相等
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            // key值相等
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            // key值不相等
            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
            // 目标位置上有key值相等的元素,将新的value覆盖旧的value
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        // 数组扩容
        resize();
    afterNodeInsertion(evict);
    return null;
}
复制代码

get(key) 方法获取对象

当获取对象时,首先跟put方法存储元素一样,也是先调用hash函数计算key的hash值, 然后计算hash & (table.length - 1) 的结果就是key的hash值在数组table中的位置bucket, 根据bucket获取该位置上的元素,判断key值是否相等,如果相等直接返回对象的value值。 如果不相等,则遍历链表,比较key值,直到找到key值相等的节点,如果没有找到则返回null。

JDK1.8中get方法源码

/**
 * Returns the value to which the specified key is mapped,
 * or {@code null} if this map contains no mapping for the key.
 *
 * <p>More formally, if this map contains a mapping from a key
 * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
 * key.equals(k))}, then this method returns {@code v}; otherwise
 * it returns {@code null}.  (There can be at most one such mapping.)
 *
 * <p>A return value of {@code null} does not <i>necessarily</i>
 * indicate that the map contains no mapping for the key; it's also
 * possible that the map explicitly maps the key to {@code null}.
 * The {@link #containsKey containsKey} operation may be used to
 * distinguish these two cases.
 *
 * @see #put(Object, Object)
 */
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) {
        // 找到hash值在数组位置上的元素
        if (first.hash == hash && // always check first node
            ((k = first.key) == key || (key != null && key.equals(k))))
            // 比较key值是否相等
            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;
}
复制代码

本文主要分析了HashMap存储对象和获取对象的过程,重点介绍了数组和链表在HashMap底层的使用。

更多精彩内容请关注公众号 geekymv,喜欢请分享给更多的朋友哦」

文章分类
后端
文章标签