HashMap的实现原理及源码浅析

HashMap的实现原理

HashMap使用的数据结构是HashTable + 链表/红黑树。

image-20200912171003156

当创建一个HashMap时,会先创建出一个HashTable:Node<K,V>[] table;

需要注意的是HashTable并不是一种特殊的类型,它本质上还是一个数组,只不过它是根据元素的hash值来决定元素在数组中的位置,所以叫做HashTable。

image-20200912171327194

当插入一对KeyValue时,会根据Key的Hash值来决定其在HashTable中的栏位:tab[i = (n - 1) & hash])

image-20200912172112180

如果该栏位已经被占用,则用该栏位当作头节点创建一个链表,把新的key-value插到链表中

image-20200912172410262

当hash值相同的key越来越多,这个链表也就越来越长,链表过长,效率就会变低。

因此,在JDK1.8之后,当链表长度大于8之后,会把这个链表转换成红黑树的结构

image-20200912172730576

浅析HashMap源码

HashMap中的HashTable的定义如下

Node<K,V>[] table;

需要注意的是HashTable并不是一种特殊的类型,它本质上还是一个数组,只不过它是根据元素的hash值来决定元素在数组中的位置,所以叫做HashTable。

另外可以看到HashTable中保存的是Node类型的元素,Node类的源码如下

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

很显然,这是一个链表的节点的定义(Node<K,V> next;)。

当链表长度大于8时,会转换成红黑树,转换成红黑树之后的节点类习是TreeNode,它的父类是Node

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
    TreeNode<K,V> parent;  // red-black tree links
    TreeNode<K,V> left;
    TreeNode<K,V> right;
    TreeNode<K,V> prev;    // needed to unlink next upon deletion
    boolean red;
}

也很容易看出来就是一个红黑树节点的结构

put方法(增/改)

HashMap添加元素最常用的方法就是put,

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

从源码中可以看到这里调用了putVal,并传入了5个参数,本文只关注前三个参数

  1. int hash:key的哈希值
  2. K key: key
  3. V value: value
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)	// 如果HashTable是空,或者HashTable的长度是1,则创建一个
        n = (tab = resize()).length;
    // 通过tab[i = (n - 1) & hash]找到key在HashTable中对应的栏位,如果该栏位是NULL,则在在这个栏位为这个key创建一个节点
    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 &&	// 如果头节点的key和要插入的节点的key相同,就用e记下插入新的节点的位,后面会用把头节点的value替换成要插入的节点的value
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)	// 如果不是改头节点, 且HashTable中的节点的数据结构已经变成红黑树,则调用红黑树插入元素的方法插入新的节点
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {	// 如果不是要改头节点, 且HashTable中的节点的数据结构还是链表
            for (int binCount = 0; ; ++binCount) { // 遍历链表看有没有是否已经存在相同的key
                if ((e = p.next) == null) {        // 遍历链表结束,且不存在相同的key
                    p.next = newNode(hash, key, value, null); // 插入新节点
                    if (binCount >= TREEIFY_THRESHOLD - 1) 	  // 判断是否需要转化成红黑树的结构
                        treeifyBin(tab, hash);		// 把链表转成红黑树
                    break;
                }
                if (e.hash == hash && // 在链表中找打相同的key, 跳出循环,e已经记录下该节点
                    ((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; // 把该相同的key对应的valu改成新的value
            afterNodeAccess(e);
            return oldValue;	// map中元素的数量没有变,直接返会
        }
    }
    ++modCount;		// 修改map中元素的数量
    if (++size > threshold) // 判断是否需要扩容
        resize();  // 扩容
    afterNodeInsertion(evict);
    return null;
}

remove方法(删)

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

实际上调用的是removeNode方法,这个方法有五个参数

  1. int hash: key的hash值
  2. Object key: key
  3. Object value: value
  4. bool matchValue: 如果是true, 则当value也相等时才删除该节点
  5. bool movable: 因为红黑树在删除某个节点之后,需要调整其他节点的位置来维持红黑树的结果,所以这个参数为false时则不改变红黑树中其他节点的位置
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;
    if ((tab = table) != null && (n = tab.length) > 0 &&	// 如果HashTable不为NULL,
        (p = tab[index = (n - 1) & hash]) != null) {		// 并且HashTable该key的Hash值对应的栏位上不为NULL
        Node<K,V> node = null, e; K k; V v;
        // 遍历链表/红黑树找到对应的node
        if (p.hash == hash &&	// 如果是链表或者红黑树的头节点,则记录下该节点
            ((k = p.key) == key || (key != null && key.equals(k))))
            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);
            }
        }
        // 如果key对应的node存在并且(不需要value也相同,或者需要判断value相同并且value是相同的),则删除该节点
        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;
            // 更新map的size和元素个数的信息
            ++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;
}

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 && // 如果HashTable不为NULL,
        (first = tab[(n - 1) & hash]) != null) {         // 并且HashTable该key的Hash值对应的栏位上不为NULL
        if (first.hash == hash && // 如果目标节点是头节点,则直接返回
            ((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;	// 遍历完没有找打目标节点,说明不存在,返回NULL
}

遍历HashMap

遍历entrySet

遍历entrySet时,实际上是拿EntrySet的迭代器EntryIterator进行遍历的。

final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
    public final Iterator<Map.Entry<K,V>> iterator() {
        return new EntryIterator();
    }
}

EntryIterator的定义如下

final class EntryIterator extends HashIterator
    implements Iterator<Map.Entry<K,V>> {
    public final Map.Entry<K,V> next() { return nextNode(); }
}

调用EntryIterator类中的next方法实际上调用的是其父类HashIterator中的nextNode方法

abstract class HashIterator {
    Node<K,V> next;        // next entry to return
    Node<K,V> current;     // current entry
    int index;             // current slot
    ...
	final Node<K,V> nextNode() {
        Node<K,V>[] t;
        Node<K,V> e = next;		// 拿到下一个元素
		... 
        // 移动current和next的位置
        if ((next = (current = e).next) == null // 把next赋值给current,并把next移动到next.next
            && (t = table) != null) {			// 如果新的next是空值并且hash table不为空
            do {} while (index < t.length && (next = t[index++]) == null); // 在hash table中找到下一个不为空的栏位,并且把该栏位的第一个元素赋值给next
        }
        return e;	// 返回下一个元素
    }
    ...
}

遍历keySet

遍历entrySet时,实际上是拿KeySet的迭代器KeyIterator进行遍历的。

final class KeySet extends AbstractSet<K> {
	...
    
    public final Iterator<K> iterator()     { return new KeyIterator(); }

	...
}

KeyIterator的实现如下。

final class KeyIterator extends HashIterator
    implements Iterator<K> {
    public final K next() { return nextNode().key; }
}

可以看到调用KeyIterator类中的next方法,实际上调用的是其父类HashIterator中的nextNode方法拿到Node,再拿到key来拿到下一个key的

遍历values

遍历Values时,实际上是拿Values的迭代器ValueIterator进行遍历的。

final class Values extends AbstractCollection<V> {
	...
    public final Iterator<V> iterator()     { return new ValueIterator(); }
	...
}

ValueIterator的实现如下。

final class ValueIterator extends HashIterator
    implements Iterator<V> {
    public final V next() { return nextNode().value; }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值