Follow me,手撕HashMap源码jdk7版

前情提要

为什么分析jdk7,不直接分析jdk8?
jdk8的源码做了大幅的改动,已经很复杂了。分析jdk7可以快速理解HashMap设计思想,以及HashMap存在的缺点,知道jdk8为什么要做这些改动。

HashMap数据结构

HashMap底层数据结构是数组和单链表,对key计算hashCode散列到数组中,相同hashCode的key添加的同一个链表中。
在这里插入图片描述

HashMap有哪些属性

// 默认容量16,2的4次方
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 默认负载因子,容量阈值超过75%的时候会触发扩容,
// 也就是超过16*0.0.75=12个。设置太小会频繁扩容,设置太大影响查询效率。
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 容量最大值
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认空数组,并不是大家想象的容量16,那是在put的时候初始化的
static final Entry<?,?>[] EMPTY_TABLE = {};
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;
    int hash;
}

如何初始化HashMap

// 无参初始化
public HashMap() {
    this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}

// 指定容量初始化
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

// initialCapacity默认容量16,loadFactor默认负载因子0.75
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;
}

put 方法

public V put(K key, V value) {
    // 是空数组,第一次初始化
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    
    // 如果key是null,就调用put null的方法
    if (key == null)
        return putForNullKey(value);
    // 计算key的hash值
    int hash = hash(key);
    // 计算key在Entry数组中的位置,相当于对数组长度求余
    int i = indexFor(hash, table.length);
    // 遍历该位置上的链表
    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;
            return oldValue;
        }
    }

    modCount++;
    // 没找到,就添加
    addEntry(hash, key, value, i);
    return null;
}
// 第一次初始化时调用
private void inflateTable(int toSize) {
    // 找到大于等于size的2的幂次方
    int capacity = roundUpToPowerOf2(toSize);

    // 计算阈值,16 * 0.75 = 12
    threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
    table = new Entry[capacity];
}
// key是null的put方法
private V putForNullKey(V value) {
    // 遍历下标是0的数组,找到了就覆盖并返回旧值
    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;
}
// hashCode逻辑与(length-1),相当于对(length-1)求余,
// 所以要保证金数组长度是2的倍数
static int indexFor(int h, int length) {
    return h & (length-1);
}
// 添加元素,bucketIndex表示数组下标
void addEntry(int hash, K key, V value, int bucketIndex) {
    // 元素个数大于阈值就扩容
    if ((size >= threshold) && (null != table[bucketIndex])) {
        // 2倍扩容
        resize(2 * table.length);
        hash = (null != key) ? hash(key) : 0;
        // 扩容后,重新计算数组下标位置
        bucketIndex = indexFor(hash, table.length);
    }

    // 创建元素节点
    createEntry(hash, key, value, bucketIndex);
}
// 扩容
void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    // 数组最大扩容到2的30次方
    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;
        }
    }
}
// 创建元素,放在头节点
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) {
    // key是null,调用单独方法
    if (key == null)
        return getForNullKey();
    Entry<K,V> entry = getEntry(key);
    return null == entry ? null : entry.getValue();
}
// key是null,遍历数组下标是0的链表
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;
}
// 获取Entry数组
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;
}

看完源码,我们试一下回答一些常见的面试题。

常见面试题

HashMap的put方法逻辑

判断entry是否是空数组,如果是初始化一个长度是16,阈值是12的数组
判断key是否等于null,如果是null,就放在下标是0的数组位置上,并插入头结点
对key的hashCode二次hash,并对(length-1)逻辑与,算出数组下标位置
遍历该下标位置上的链表,如果找到该key,就覆盖旧值并返回
判断当前元素个数是否大于阈值,如果大于就执行2倍扩容,把原数组的元素重新hash到新数组中
用当前key创建一个节点,插到下标数组链表的头结点

为什么HashMap的容量必须是2的倍数

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

计算机中,与运算比求余运算更快,采用了hashCode&(length-1)。
假如length是16,(length-1)的二进制就是 1111,比15小的数逻辑与之后就是自身,比15大的数,只有低4位的数才能运算出值。是为了更方便与运算。
HashMap线程不安全体现在哪些方面?
由于hash冲突的时候插入链表,采用的是头插法,导致扩容后链表的顺序和原来顺序相反,多个线程同时扩容会出现环形链表,get的时候陷入死循环。

读者福利

我这边整理了很多家互联网公司的面试资料(含答案),如下图
有需要的话可以免费获取!
部分资料截图
获取方式!关注+点赞+评论666
点击即可免费领取

(思考)HashMap还有哪些缺点

使用单链表解决hash冲突,导致最坏的情况get的效率降至O(N)
链表采用头插法,导致多线程扩容出现环形链表
扩容需要把每个元素重新hash放到新数组里,性能太差

针对这些缺点,你有没有好的解决办法,好在这些问题都在jdk8得到解决,下篇一块手撕jdk8 HashMap源码。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章