JavaJAVA基础Java

HashMap原理知识点速查

2018-04-24  本文已影响671人  林檎果

数据结构之哈希表

HashMap的结构

transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;//存储指向下一个Entry的引用,单链表结构
        int hash;//对key的hashcode值进行hash运算后得到的值,存储在Entry,避免重复计算
...
}

HashMap的源码分析:插入

public V put(K key, V value) {
        //其允许存放null的key和null的value,放在table[0]
        if (key == null)
            return putForNullKey(value);
       
        int hash = hash(key);
        //得到键的哈希值,用来获取数组中的索引
        int i = indexFor(hash, table.length);
        //如果i处的Entry不为null,则需要在链表中添加,但是添加前需要看是否已存在,存在返回旧值,不存在则最终addEntry。
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
        //添加前看是否需要扩容
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }

        createEntry(hash, key, value, bucketIndex);
}

void createEntry(int hash, K key, V value, int bucketIndex) {
        // 获取指定 bucketIndex 索引处的 Entry
        Entry<K,V> e = table[bucketIndex];
        // 将新创建的 Entry 放入 bucketIndex 索引处,并让新的 Entry 指向原来的 Entr
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
}

HashMap的源码分析:读取

    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);

        return null == entry ? null : entry.getValue();
    }
    final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key);
        //通过哈希得到的index的e不为空则继续搜索链表
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

HashMap的性能参数

HashMap的扩容

参考

  1. Java集合学习1:HashMap的实现原理,李大辉,http://tracylihui.github.io/2015/07/01/Java%E9%9B%86%E5%90%88%E5%AD%A6%E4%B9%A01%EF%BC%9AHashMap%E7%9A%84%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86/
  2. HashMap实现原理及源码分析,dreamcatcher-cx,http://www.cnblogs.com/chengxiao/p/6059914.html

关于我:

linxinzhe,全栈工程师,目前供职于某500强通信企业。人工智能,区块链爱好者。

GitHub:https://github.com/linxinzhe

欢迎留言讨论,也欢迎关注我~
我也会关注你的哦!

上一篇下一篇

猜你喜欢

热点阅读