HashMap源码解析

先看一道题

HashMap,put100次数据,key值不重复,但是监控发现key的hash冲突了2次,那么现在的Entry[]全部长度和非空长度分别是多少?
a.100,98
b.100,100
c.128,100
d.128,98
如果不知道这道题问题什么,怎么做。那么也许该了解一下HashMap,下面就说一下HashMap。

什么是hash ?
  • 简单理解,可以当作是一种数学函数,输入x 得到 y 。 不过这个函数比较特殊,从 x与y基本上是一一对应的,而且, 不可能从 y 中得到 x (不可逆)。
  • 函数的性质是从一个 x 中只能得到一个 y ,而y有可能对应不止一个x, 这是函数定义。
  • 那么, 虽说hash函数比较特殊,一个 y 基本只有一个x, 那么有没有可能一个 y 对应不止一个x 。
  • 是的, 有可能的, 这种情况就是hash碰撞, 碰撞越多, 说明该hash函数越差。
  • 一般情况,hash输出也是字符串。 HashMap 这里的hash是整数, 确切的说,是对象的 hashCode函数返回值。
  • hashCode 函数一般不覆盖,相同一个对象, 理应只得到一个 hashCode。
HashMap的底层结构
  • 我们之前了解到ArrayList是用数组实现的, 自带索引,不改结构的前提下,操作效率是比较好,增加时则需要扩容。
  • 而LinkedList则是用链表实现的,本身没有索引, 用指针维持列表关系,在改变结构方面是比较快的,并且不需要扩容。
  • 那么, 能否把这两种结构优点结合起来呢? 这就是HashMap的结构, 数组+链表。其存储结构简化如下图:
    在这里插入图片描述
分析HashMap.
  • 首先看看 HashMap的属性.
    /**
    *默认的初始化容量. 通过位运算表示. 1的位表示. 左移4位,即 2的4次方. 后面会知道为什么要用位运算来做. 
    */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    /**
     *最大的容量. 2的30次方. 
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;
    /**
     * 默认的加载因子. 当size达到 容量threshold * 加载因子, 就[可能]会进行扩容 
     * 用 0.75 是综合时间和空间的利用率来考虑的结果. 
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    /**
     * 非null空数组. 
     */
    static final Entry<?,?>[] EMPTY_TABLE = {};
    /**
     * 即 hashMap的hash桶, 每个桶都用来存放链表. 初始指向非null空桶. 
     */
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
    /**
     * 插入的元素. 长度
     */
    transient int size;
    /**
     *扩容值. 当size达到 容量threshold  就[可能]会进行扩容 
     */
    int threshold;
    /**
     * 加载因子. 当size达到 容量threshold * 加载因子, 就[可能]会进行扩容 
     */
    final float loadFactor;
    /**
     * 修改次数. 用于迭代时快速失败. 具体见. ArrayList. 
     */
    transient int modCount;
  • 构造函数:
    /**
    *使用指定容量和加载因子. 初始话hashmap 
    */
    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);
        // 容量和加载因子都合法.(非负数), 并且此处使用延迟扩充. 在真正put的时候才使用这些值. 去初始化 table
        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        init();
    }
    /**
    * Initialization hook for subclasses. 注释说得很明白. 为子类保留的方法. hashmap的子类linkedHash就覆盖了这个方法.
    */
    void init() {
    }
    /**
     *指定容量, 使用默认加载因子0.75
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 使用默认容量和加载因子. 16和0.75
     */
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 根据已有的map床架hashmap. 容量为 取传入的map/默认加载因子+1 (好处是put的时候不用再次扩容)或者 默认容量 较大值.
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        inflateTable(threshold);
        putAllForCreate(m);   
    }

  • 构造函数这里还有一个方法,inflateTable(threshold);在put的时候也会调用到这个方法, 这个方法是真正扩充桶数组的操作。 如下:
    /**
     * 扩充hash桶数组.
     */
    private void inflateTable(int toSize) {
        int capacity = roundUpToPowerOf2(toSize); //取得一个离 toSize距离最近的2次方值. 

        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);  // 扩容水位. size达到这个值就可能会进行扩容. 
        table = new Entry[capacity];  //桶大小. 
        initHashSeedAsNeeded(capacity);
    }
    /**
    * 这个方法的目的, 就是根据输入. 获取离该输入最近的2次方值. 例如 100则是 128
    * 算法流程.
    * 判断是否超过最大容量, 不超过, 则取.number最高位2次方值再移一位(乘2). 
    * 如, number  =  20 .  二进制码为  10100  .  通过 Integer.highestOneBit 得到 100000 (如果输入是0,则返回0). 并把 100000 左移一位, 得到 1000000 即 2的6次方, 32. 如果number是0 则返回1. 
    */
    private static int roundUpToPowerOf2(int number) {
        int rounded = number >= MAXIMUM_CAPACITY
                ? MAXIMUM_CAPACITY
                : (rounded = Integer.highestOneBit(number)) != 0
                    ? (Integer.bitCount(number) > 1) ? rounded << 1 : rounded
                    : 1;
        return rounded;
    }

    /**初始化 hash种子. 类似. hash算法. 128位和256得到结果是不同. hashCode也需要一个类似东西. 去得到hash数. 这就是 hash seed的作用. 
     */
    final boolean initHashSeedAsNeeded(int capacity) {
        boolean currentAltHashing = hashSeed != 0;
        boolean useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        boolean switching = currentAltHashing ^ useAltHashing;
        if (switching) {
            hashSeed = useAltHashing
                ? sun.misc.Hashing.randomHashSeed(this)
                : 0;
        }
        return switching;
    }

  • 我们在hashmap里还找到一个内部类,这个类是链表节点, HashMap的table成员是这个类的对象组成的数组, 从中可以看出, HashMap 的底层为 数组 + 单向链表。
static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;   //同一个hash桶中形成链表. 
        int hash;

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

        public final K getKey() {
            return key;
        }

        public final V getValue() {
            return value;
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }

        public final int hashCode() {
            return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
        }

        public final String toString() {
            return getKey() + "=" + getValue();
        }

        /**
         * This method is invoked whenever the value in an entry is
         * overwritten by an invocation of put(k,v) for a key k that's already
         * in the HashMap.
         */
        void recordAccess(HashMap<K,V> m) {
        }

        /**
         * This method is invoked whenever the entry is
         * removed from the table.
         */
        void recordRemoval(HashMap<K,V> m) {
        }
    }
  • 接下来我们看看 put方法。
   public V put(K key, V value) {
        if (table == EMPTY_TABLE) {  
            inflateTable(threshold);  // 上文提到了. 这个方法是真正初始化或扩充桶数组的操作.
        }
        if (key == null)     //增加对 key为null的支持. key=null的. 都放在第一个位置上.
            return putForNullKey(value);   
        int hash = hash(key);   // 取得key的hash, 先忽略具体算法.
        int i = indexFor(hash, table.length);   //根据key的hash和容量, 找到key对应hash桶位置.先忽略具体算法.
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {  //检查该桶中是否已经有 相同的key. 有的话替换 value并返回. 
            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;
            }
        }
        //key的hash桶里不存在相同的key
        modCount++;  //结构变换次数+1.
        addEntry(hash, key, value, i);  //真正插入操作.
        return null;
    }

    /**
     * 真正的插入操作. 扩容, 将元素放到hash桶都在这个方法里.
     */
    void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) { //此处达到水位之后不一定扩容. 只有待放入的hash桶不为null才扩容. 否则暂时不扩容. 
            resize(2 * table.length);   //以2倍的方式(目标)扩容. 这样是有一定好处. 后面说.  
            hash = (null != key) ? hash(key) : 0; //扩容之后,重新获取key的hash. key为null是hash为0.  resize之后 hashSeed也会改变. 所以要重新获取 hash.
            bucketIndex = indexFor(hash, table.length);  //扩容之后,重新获取key位置. 
        }

        createEntry(hash, key, value, bucketIndex);
    }
    /**
     * 把 k-v 放进 table[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为null的支持.  key为null的放在 table[0]上. 并且. 只有一个.
     */
    private V putForNullKey(V value) {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {  //查找是否已经有key=null的元素. 是的话替换 value 并返回. 
            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这里有几个关键方法,我们来看一看。
    /**
     * 通过 hashSeed和key的hashCode. 可以产生 hashCode  - 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();
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

    /**
     * 通过 indexFor和桶长度. 得到. 元素要放到哪个桶里. 
     * 正常情况下. 我们会用 % 来得到. 但是此处. 由于控制了. length为2的次方. 因此可以通过位运算更加快速高效得到. 桶位置. 
     */
    static int indexFor(int h, int length) {
        return h & (length-1); // length must be a non-zero power of 2";
    }

    /**
     *
     */
    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));  //重新产生hashSeed. 并把原来桶数组里的元素转移到新的桶数组. 
        table = newTable;
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }
  • 以上就是put方法大概的逻辑,理解了put方法之后,其实其它一些方法就比较容易理解了。 如下:
/**
    containe算法基本和get相似. 大概看下源码即可理解. 
*/  
public V get(Object key) {
        if (key == null)
            return getForNullKey();   //对key为null特殊处理, 检查第一个桶即可. 
        Entry<K,V> entry = getEntry(key);  //key不为null,则通过key的hash和indexFor算法,确定key可能落在的桶. 再检查这个桶里有没有key相同的entry即可获取value. 

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

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

 public boolean containsValue(Object value) {
        if (value == null)
            return containsNullValue();

        Entry[] tab = table;
        for (int i = 0; i < tab.length ; i++)
            for (Entry e = tab[i] ; e != null ; e = e.next)
                if (value.equals(e.value))
                    return true;
        return false;
    }

public boolean containsKey(Object key) {
        return getEntry(key) != null;
    }
  • 至此, HashMap基本可以理解, 但是有两个还稍微讲一下, 一个是迭代, 一个序列化。
    • 迭代比较简单,如entrySet 返回一个HashMap的内部类 EntrySet, 这个EntrySet 的迭代器方法, 直接调用HashMap方法返回一个entrySet迭代器, keySet和valueSet类似。
    • 序列化则是由于桶数组等 部分属性用了transient, 因此, HashMap内部实现部分序列化, 看如下源码基本可以理解。
    /**
     *
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws IOException
    {
        s.defaultWriteObject();
        //写 length
        if (table==EMPTY_TABLE) {  //空数组时,桶数未初始化. 要调用一下roundUpToPowerOf2来初始化桶数量 
            s.writeInt(roundUpToPowerOf2(threshold)); 
        } else {
           s.writeInt(table.length);
        }
        s.writeInt(size);  // 写size
        if (size > 0) { // 不为空时, 把key和value分别写入
            for(Map.Entry<K,V> e : entrySet0()) {
                s.writeObject(e.getKey());
                s.writeObject(e.getValue());
            }
        }
    }
    /**
     * 
     */
    private void readObject(java.io.ObjectInputStream s)
         throws IOException, ClassNotFoundException
    {
        s.defaultReadObject();
        if (loadFactor <= 0 || Float.isNaN(loadFactor)) { 
            throw new InvalidObjectException("Illegal load factor: " +
                                               loadFactor);
        }
        table = (Entry<K,V>[]) EMPTY_TABLE;
        s.readInt();   //读 length
        int mappings = s.readInt();  //读size
        if (mappings < 0)
            throw new InvalidObjectException("Illegal mappings count: " +
                                               mappings);
        int capacity = (int) Math.min(
                    mappings * Math.min(1 / loadFactor, 4.0f),
                    // we have limits...
                    HashMap.MAXIMUM_CAPACITY);

        // allocate the bucket array;
        if (mappings > 0) {
            inflateTable(capacity);
        } else {
            threshold = capacity;
        }
        init();  // Give subclass a chance to do its thing.
        // Read the keys and values, and put the mappings in the HashMap
        for (int i = 0; i < mappings; i++) {  //分别读每个对象. 
            K key = (K) s.readObject();
            V value = (V) s.readObject();
            putForCreate(key, value);  //见上. 
        }
    }
  • 到这里, 我们可以解决文章开头的题目了:
    • 距离100最小的2的多次方值为128, 而128 * 0.75 = 96 ; 理论上, 在put第97个时就应该扩容到256了, 为什么没有呢?
    • 如下, 我们可以看到, size>threshold时,只有在获取到的桶非空, 才会进行扩容。 所以 128 和 256 都是合理的, 两次冲突,而数组里的非空的,链表数应该为 98, 其中有两个链表有两个 entry对象(双节点链表),其余的是单节点链表
void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) { //此处达到水位之后不一定扩容. 只有待放入的hash桶不为null才扩容. 否则暂时不扩容. 
            resize(2 * table.length);   //以2倍的方式(目标)扩容. 这样是有一定好处. 后面说.  
            hash = (null != key) ? hash(key) : 0; //扩容之后,重新获取key的hash. key为null是hash为0.  resize之后 hashSeed也会改变. 所以要重新获取 hash.
            bucketIndex = indexFor(hash, table.length);  //扩容之后,重新获取key位置. 
        }

        createEntry(hash, key, value, bucketIndex);
    }
简单总结:
  • HashMap 综合了数组和链表的优点.其实际是一个 “单向链表数组”
  • 扩容:HashMap 中存放的key-value对的个数size,该个数决定了数组的扩容(**size>=threshold**时,扩容),而非 table中的所占用的桶的个数来决定是否扩容
  • 扩容取决于元素个数,即size >= (threshold=table.length * loadFactor) 。
  • HashMap 的高效取决于其内部hash函数, 而内部hash函数依赖key的hashCode,因此hashCode减少hash碰撞, 对HashMap的性能至关重要,不应轻易覆盖Key的hashCode实现, 极端情况下, 如hashCode返回常数值1, HashMap将成为一个性能极差的单向链表(例如会不断进行无意义的扩容,但只使用到一个链表,不会使用到数组其它链表)。
  • 从源码中我们看出,hashmap是没有和同步的代码的, 因此 hashMap是线程不安全的,要线程安全, 应使用其子类, ConcurrentHashMap
还有
  • 前面还留有一个问题, 为什么要用位运算来初始化 DEFAULT_INITIAL_CAPACITY等默认值
  • 从上面我们可以看到, HashMap的容量, 初始化传入即使不是 2 的多次方, 在第一次 put的时候也会初始为离传入的initCapacity最近的2次方值。
  • 所以, 用位运算来初始化 DEFAULT_INITIAL_CAPACITY是合理,但是, 为什么put等初始化检查时要弄成这个值呢?
  • 仔细看的话就在上面就能找得到原因了,因为这样子更加高效(位运算高效)。 可以更快速的通过位运算取得元素位置,由此我们也可以知道,在resize时为什么要通过2倍原容量。 resize(2 * table.length) ,这样子可以保持桶容量为 2 的次方。
static int indexFor(int h, int length) {
        // length must be a non-zero power of 2";
        return h & (length-1);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值