美文网首页
HashMap原理介绍

HashMap原理介绍

作者: yuLiangC | 来源:发表于2021-01-31 18:56 被阅读0次

今天咋来聊聊hashMap的原理。
hashMap是使用频率最高的集合对象之一了,说到集合框架就不得不先来看一幅图。

image.png

可以看出,hashMap是AbstractMap的子类,而AbstractMap又实现了map接口,map接口定义了一系列的增删改查方法,使用键值对来存储数据。
首先看看构造函数。

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

注释已经说的很清楚了,就是默认大小是16,然后负载因子是0.75,也就是说每次存储数据满了之后再以当前大小的0.75倍来进行扩容,比如当前大小是16,满16了就再增加16*0.75的大小。
然后看看put函数。

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

添加数据的时候会先对key进行一个hash值计算,其他两个参数暂且忽略。接下来深入putVal函数瞅瞅,这个函数大致可以看出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;
    }

可以看出,hashmap维护了一个Node<K,V>节点的数组tab,通过hash冲突得到一个小于table数组长度的数值,这个数值作为存放该节点的下标值(index)。这个Node是一个静态类,包含了k,v,hash值和下一个node对象,即链表结构。如下图:

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

每次添加一个不同的k,就先通过ke计算出其hash值,再通过hash值计算其数组的下标(index)值,如果不存在,则创建一个新的节点;如果存在,则遍历该table[index]对应的链表节点,若是key一致,则更新value,若是不一致,则在生成一个新的Node节点插入表头。
当然,在添加之前和之后都会进行容量检测,也就是resize()函数,若是检测到当前大小等于或者超过table的大小时,就会进行扩容操作。


image.png

接下来看看get()函数。

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

很显然,重点就在getNode()函数中:

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

有了put的过程,get就好理解多了,首先也是通过key算出hash,然后用hash算出应该存储在table中的index,然后遍历table[index],然后比对key,找到相同的key,则取出其value。

相关文章

网友评论

      本文标题:HashMap原理介绍

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