Java源码分析:HashMap

HashMap源码分析

一、HashMap概述

hashMap基于hash表,允许使用null键值,不同步(和hashTable的区别),而且不保证顺序不变。hashMap线程不安全,可以使用下面的代码来获取线程安全的hashMap。

Map map = Collections.synchronizedMap(new HashMap());

二、HashMap的数据结构

HashMap的底层采用数组和链表来实现,计算散列码来决定存储的位置。HashMap使用链表来解决hash冲突。
《Java源码分析:HashMap》

    //静态内部类entry,它是处理hash冲突时的链表,实现了Map.Entry接口,
    即实现getKey(), getValue(), setValue(V value), equals(Object o), hashCode()这些函数  
    static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        //下一个节点
        Entry<K,V> next;
        int hash;

        /** *创建一个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;
        }
        // 判断两个Entry是否相等 
        // 若两个Entry的“key”和“value”都相等,则返回true。 
        // 否则,返回false 
        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;
        }
        //k、v综合起来实现hashCode
        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) {
        }
    }

HashMap其实就是一个Entry数组,Entry对象中包含了键和值,其中next也是一个Entry对象,它就是用来处理hash冲突的,形成一个链表。

三、源码分析

1、关键属性

//初始默认值 16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

    //默认的加载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //没扩容前的空实例
    static final Entry<?,?>[] EMPTY_TABLE = {};

    //存储元素的实体数组
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

    //临界值 当实际大小超过临界值时,会进行扩容threshold = 加载因子*容量
    int threshold; 
    //被修改次数
    transient int modCount;

loadFactor因子表示Hash表中的填满程度,如果加载因子越打,说明空间利用率高,但是冲突的机会更大,查找效率降低。这种“冲突的机会”和“空间利用率”也是时空之间的一种折衷。

2、构造方法
下面看看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);

        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        //初始化,源码里面什么都没有 主要是提供给子类在map初始化的时候覆盖使用
        init();
    }


    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    //默认容量
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }

    //直接装填一个已有的map<K,V>
    public HashMap(Map<? extends K, ? extends V> m) {
        //比较已有map/加载因子+1 和 初始容量的大小
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        //进行扩容
        inflateTable(threshold);

        putAllForCreate(m);
    }

下面的代码是介绍如何扩容和装填的。

private void inflateTable(int toSize) {
    // 进行扩容
    // Find a power of 2 >= toSize
    //用工具扩容保障容量为2的整数次幂
    int capacity = roundUpToPowerOf2(toSize);
    //获得边界值
    threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
    //初始化entry数组
    table = new Entry[capacity];
    //初始化hashseed,hashSeed用于计算key的hash值,
    它与key的hashCode进行按位异或运算。这个hashSeed是一个与实例相关的随机值,主要用于解决hash冲突。
    initHashSeedAsNeeded(capacity);
}
//这里是工具类,始终将hashMap的size扩充为2的整数次幂
//highestOneBit(number)返回一个数最左边的1位代表的整数
//比如170 二进制10101010 返回10000000代表的整数128 
private static int roundUpToPowerOf2(int number) {
    // assert number >= 0 : "number must be non-negative";
    int rounded = number >= MAXIMUM_CAPACITY
            ? MAXIMUM_CAPACITY
            : (rounded = Integer.highestOneBit(number)) != 0
                ? (Integer.bitCount(number) > 1) ? rounded << 1 : rounded
                : 1;

    return rounded;
}

为什么hash表大小一定要2的n次幂?这里给大家看hashMap的散列算法是如何实现的。

     /** * Returns index for hash code h. */
    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);
    }

这里主要是用hash值和 hash的size-1相与。举个例子,如果size = 50,减一后49的二进制为11001,任何一个数和它相与的结果只能有8种情况:

  • 000000:0
  • 000001:1
  • 010000:16
  • 010001:17
  • 100000:32
  • 100001:33
  • 110000:48
  • 110001:49

但是如果是32,它的二进制是100000,减1后为:11111 ,这样就会出现32种情况,做大最大散列。

下面再来看put和get操作:

 public V put(K key, V value) {
        //如果数组为空则扩充
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        //如果key为空则跳到处理key为空的方法里
        if (key == null)
            return putForNullKey(value);
        //key不为空时,计算hash值
        int hash = hash(key);
        //计算索引
        int i = indexFor(hash, table.length);
        //如果Key存在则覆盖原来的值,如果冲突则从数组索引的后面链表处继续添加
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            //k的hash完全相等则替换value,不相等则跳到addEntry方法
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        //修改次数增加
        modCount++;
        //添加新Entry
        addEntry(hash, key, value, i);
        return null;
    }
        //这里是添加null key的方法
        private V putForNullKey(V value) {
        //如果null key 上有值则覆盖,无值则添加
        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;
    }

    //get 主要是通过key获取entry
    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);

        return null == entry ? null : entry.getValue();
    }
    //首先获取key的hash code,用indexFor定位到数组索引,然后再从数组索引当作链表头往后找
    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;
    }

    void addEntry(int hash, K key, V value, int bucketIndex) {
        //根据hash code值的索引进行扩容
        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);
    }

看到这里,就到了resize方法了,看看resize方法的源码:

void resize(int newCapacity) {
        //首先确定新的值,然后调用transfer方法
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

        Entry[] newTable = new Entry[newCapacity];
        //这里传入新的table和hashseed
        transfer(newTable, initHashSeedAsNeeded(newCapacity));
        table = newTable;
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }   
     //这里是最耗时的地方,遍历之前的table,重新装填
     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);
                }
                //根据新的hash计算索引位置
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

hashMap的主要代码就是上面这些了,最精妙的我觉得是那个2的N次方做散列。

    原文作者:闻_安
    原文地址: https://blog.csdn.net/mr253727942/article/details/50780376
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞