Java1.7的HashMap源码分析-面试必备技能

  • HashMap是现在用的最多的map,HashMap的源码可以说是面试必备技能,今天我们试着分析一下jdk1.7下的源码。
  • 先说结论:数组加链表

 hashmap

一、先看整体的数据结构

首先我们注意到数据是存放在一个Entry<K,V>数组里面,默认大小16.

public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable
{

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * An empty table instance to share when the table is not inflated.
     */
    static final Entry<?,?>[] EMPTY_TABLE = {};

    /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     */
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

    ... ...

我们来看看Entry<K,V>长什么样

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

        /**
         * Creates new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }

        ... ...

这是一个单链表结构,next指向下一个

二、put方法

我们来解析一下最常用的put方法

public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        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;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

我们一步步来分析,首先如果table为空就初始化table

if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }

我们来看看inflateTable(threshold)方法,就是计算初始化的大小,初始化table.

    private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        int capacity = roundUpToPowerOf2(toSize);

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

接着往下走,如果key是空的处理。

        if (key == null)
            return putForNullKey(value);

进到putForNullKey()方法我们知道它是把null放到了table[0],for循环里面是已经存在的数据进行替换;如果不存在,通过addEntry添加到table.

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

回到put方法,往下走,获取hash,通过hash获取数组的下标i

        int hash = hash(key);
        int i = indexFor(hash, table.length);

接下来的for循环,是遍历下标i的链表,比较key和hash,替换相应的value

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

for循环如果找到了,会把新值替换旧值,并返回oldvalue;
如果for循环没找到,则通过addEntry()添加到table

    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) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }

总结一下:

  • 先用key生成hash,定位到数组的下标
  • 如果遍历链表,查找,找到之后替换,返回
  • 如果没找到,把数据插入到第一位

三、get方法

get方法就简单了

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

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

如果key为null,从第一位table[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;
    }

如果key不是null,走getEntry,基本就和put的逻辑反过来就行了

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

通过key,计算hash,在计算数组的下标i, 从链表的第一位开始,比较key和hash,一直往后遍历,直到找到值,返回e;
最后,如果没找到,返回null.

四、思考

  • 我们想一想,这个结构还有什么问题吗?
  • 如果hash算法不好,好多key都落在同一个下标,那么链表是不是超长?
  • 我们改天说说java1.8是怎么改进这个问题的。

 interview
推荐关注此文作者公众号:丰极,关注后回复“面试资料”即可获取百度阿里美团等大厂面试资料。

原文地址:https://www.cnblogs.com/zhangbin1989/p/13230015.html