HashMap实现原理

前言

HashMap的主干是一个数组,假设我们有3个键值对dnf:1,cf:2,lol:3,每次放的时候会根据hash函数来确定这个键值对应该放在数组的哪个位置,即index = hash(key)

1 = hash(dnf),我们将键值对放在数组下标为1的位置
这里写图片描述
3 = hash(cf)
这里写图片描述
1 = hash(lol),这时发现数组下标为1的位置已经有值了,我们把lol:3放到链表的第一位,将原先的dnf:1用链表的形式放到lol键值对的下面,因为HashMap采用的是头插法
这里写图片描述
在获取key为dnf的键值对时,1=hash(dnf),得到这个键值对在数组下标为1的位置,dnf和lol不相等,和下一个元素比较,相等返回

源码

基于jdk1.7.0_80

关注点 结论
HashMap是否允许空 key和value均允许为空
HashMap是否允许重复数据 不允许
HashMap是否有序 无序
HashMap是否线程安全 非线程安全

这里写图片描述
几个重要的属性

//初始容量是16,且容量必须是2的倍数
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

//最大容量是2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;

//负载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;

static final Entry<?,?>[] EMPTY_TABLE = {};

//HashMap的主干是一个Entry数组,在需要的时候进行扩容,长度必须是2的被数
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

//放置的key-value对的个数
transient int size;

//进行扩容的阀值,值为 capacity * load factor,即容量 * 负载因子
int threshold;

//负载因子
final float loadFactor;

//和线程安全相关,这里不讨论
transient int modCount;

transient int hashSeed = 0;

这里说一下threshold和loadFactor,threshold = capacity * load factor,即扩容的阀值=容量*负载因子,比如HashMap的容量为16,负载因子为0.75,则阀值为16*0.75=12,当HashMap中放入12个元素时,就会进行扩容

  1. 负载因子越小,容易扩容,浪费空间,但查找效率高
  2. 负载因子越大,不易扩容,对空间的利用更加充分,查找效率低(链表拉长)

存储数据的静态内部类

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,避免重复计算

    Entry(int h, K k, V v, Entry<K,V> n) {
        value = v;
        next = n;
        key = k;
        hash = h;
    }
}

构造函数(其他都是在此基础上的扩展)

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;
    threshold = initialCapacity;
    init();
}

put方法

public V put(K key, V value) {
    //hashmap的数组为空
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    if (key == null)
        return putForNullKey(value);
    //获取hash值
    int hash = hash(key);
    //找到应该放到table的哪个位置
    int i = indexFor(hash, table.length);
    //遍历table[i]位置的链表,查找相同的key,若找到则使用新的value替换oldValue,并返回oldValue
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        //如果key已经存在,将value设置为新的,并返回旧的value值
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    //将元素放到table[i],新的元素总在table[i]位置的第一个元素,原来的元素后移
    addEntry(hash, key, value, i);
    return null;
}

为空时,HashMap还没有创建这个数组,有可能用的是默认的16的初始值,还有可能自定义了长度,这时需要把数组长度变为2的最小倍数,并且这个2的倍数大于等于初始容量

private void inflateTable(int toSize) {
    //返回大于或等于最接近2的幂数
    int capacity = roundUpToPowerOf2(toSize);

    threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
    table = new Entry[capacity];
    initHashSeedAsNeeded(capacity);
}

若key为null,则将值放在table[0]这个链上

private V putForNullKey(V value) {
    for (Entry<K,V> e = table[0]; e != null; e = e.next) {
        if (e.key == null) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }
    modCount++;
    addEntry(0, null, value, 0);
    return null;
}

获取hash值

final int hash(Object k) {
    int h = hashSeed;
    if (0 != h && k instanceof String) {
        return sun.misc.Hashing.stringHash32((String) k);
    }

    h ^= k.hashCode();

    // This function ensures that hashCodes that differ only by
    // constant multiples at each bit position have a bounded
    // number of collisions (approximately 8 at default load factor).
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}

找到应该放在数组的位置

static int indexFor(int h, int length) {
    // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
    return h & (length-1);
}

添加元素

void addEntry(int hash, K key, V value, int bucketIndex) {
    //容量超过阈值,并且即将发生哈希冲突时进行扩容
    if ((size >= threshold) && (null != table[bucketIndex])) {
        //扩容为原来的2倍
        resize(2 * table.length);
        //重新计算hash值
        hash = (null != key) ? hash(key) : 0;
        bucketIndex = indexFor(hash, table.length);
    }

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

将新增加的元素放到table的第一位,并且将其他元素跟在第一个元素后面

void createEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<>(hash, key, value, e);
    size++;
}

get方法

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

    return null == entry ? null : entry.getValue();
}

从table[0]初获取key为null的值

private V getForNullKey() {
    if (size == 0) {
        return null;
    }
    for (Entry<K,V> e = table[0]; e != null; e = e.next) {
        if (e.key == null)
            return e.value;
    }
    return null;
}

key不为null时

final Entry<K,V> getEntry(Object key) {
    if (size == 0) {
        return null;
    }

    int hash = (key == null) ? 0 : hash(key);
    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;
}

resize

void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    //容量已经达到最大
    if (oldCapacity == MAXIMUM_CAPACITY) {
        threshold = Integer.MAX_VALUE;
        return;
    }

    Entry[] newTable = new Entry[newCapacity];
    transfer(newTable, initHashSeedAsNeeded(newCapacity));
    table = newTable;
    threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}

重新计算元素在新的数组中的位置,并进行复制处理

void transfer(Entry[] newTable, boolean rehash) {
    int newCapacity = newTable.length;
    for (Entry<K,V> e : table) {
        while(null != e) {
            Entry<K,V> next = e.next;
            if (rehash) {
                e.hash = null == e.key ? 0 : hash(e.key);
            }
            int i = indexFor(e.hash, newCapacity);
            e.next = newTable[i];
            newTable[i] = e;
            e = next;
        }
    }
}

知识点

HashMap的大小为什么是 2 n

HashMap确定键值对的在数组中的下标是用的是如下方法

static int indexFor(int h, int length) {
    return h & (length-1);
}

h & (length - 1) 等价于 h % length,我们假设数组的长度为15和16,hash码为8和9

h & (length - 1) h length index
8 & (15 - 1) 0100 1110 0100
9 & (15 - 1) 0101 1110 0100
8 & (16 - 1) 0100 1111 0100
9 & (16 - 1) 0101 1111 0101

可以看出数组长度为15的时候,hash码为8和9的元素被放到数组中的同一个位置形成链表,键低了查询效率,当hahs码和15-1(1110)进行&时,最后一位永远是0,这样0001,0011,0101,1001,1011,0111,1101这些位置永远不会被放置元素,这样会导致1.空间浪费大,2.增加了碰撞的几率,减慢查询的效率。当数组长度为 2 n 时, 2 n 1 的所有位都是1,如8-1=7即111,那么进行低位&运算时,值总与原来的hash值相同,降低了碰撞的概率

放入HashMap中的对象为什么要重写equals和hashCode方法

参考博客

HashMap实现原理
[1]https://www.cnblogs.com/chengxiao/p/6059914.html
[2]http://ms.csdn.net/geek/187726
[3]https://blog.csdn.net/changlei_shennan/article/details/78687719
[4]https://blog.csdn.net/world6/article/details/70053356

猜你喜欢

转载自blog.csdn.net/zzti_erlie/article/details/79823187