HashMap源码分析

mac2022-06-30  99

目录

 

1. HashMap结构特点

2. JDK7 HashMap 

    2.1 HashMap的参数

    2.2 HashMap构造函数

   2.3 HashMap添加新的应用的方法,v>

       2.3.1 put方法

      2.3.2 putForNullKey方法

      2.3.3 hash函数

      2.3.4 indexFor方法

      2.3.5 addEntry方法和createEntry方法

       2.3.6 resize方法: hashmap扩容

       2.3.7 transfer方法:扩容时将当前哈希表数据复制到新的哈希表

    2.4. HashMap获取,v>

      2.4.1 get方法

    2.4.2 getForNullKey方法

3. JDK8 HashMap

  3.1 JDK7与JDK8的区别

  3.2 HashMap参数 

  3.3 put函数

  3.3 hash函数

  3.4 resize函数


1. HashMap结构特点

HashMap基于哈希表的Map接口实现,采用Entry数组+链表存储Entry以key-value形式存储,其中key是可以允许为null但是只能是一个,并且key不允许重复(如果重复则新值覆盖旧值)。通过计算key的hash值来找Entry数组的索引,如果Entry数组索引位置上为空,则将值放入索引处,如果不为空,则插入到链表头。计算key的hash函数及插入的函数在后面会提到

HashMap存储结构

2. JDK7 HashMap 

    2.1 HashMap的参数

/** * The default initial capacity - MUST be a power of two. */ static final int DEFAULT_INITIAL_CAPACITY = 16; //默认的初始容量为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; //最大的容量为 2 ^ 30 /** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; //默认的负载因子为 0.75f /** * The table, resized as necessary. Length MUST Always be a power of two. */ transient Entry<K,V>[] table; //存放数据的Entry数组 /** * The number of key-value mappings contained in this map. */ transient int size; 记录了Map中Entry<K,V>的个数 /** * The next size value at which to resize (capacity * load factor). * @serial */ int threshold; //阈值 table为空,初始为默认16,table不为空时,为capacity*loadFactory /** * The load factor for the hash table. * * @serial */ final float loadFactor; //负载因子 /** * The number of times this HashMap has been structurally modified * Structural modifications are those that change the number of mappings in * the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException). */ transient int modCount;//记录修改次数,多线程情况下,当出现expectedModCount和ModCount不相等,抛出ConcurrentModificationException异常 /** * The default threshold of map capacity above which alternative hashing is * used for String keys. Alternative hashing reduces the incidence of * collisions due to weak hash code calculation for String keys. * <p/> * This value may be overridden by defining the system property * {@code jdk.map.althashing.threshold}. A property value of {@code 1} * forces alternative hashing to be used at all times whereas * {@code -1} value ensures that alternative hashing is never used. */ //阈值的默认值 static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;

    2.2 HashMap构造函数

public HashMap(int initialCapacity, float loadFactor) { //初始容量大于0 ,否则抛出异常 if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); //初始容量不能超过2^30 (1073741824) if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; //加载因子不能小于等于0,或者加载因子不能是非数字,否则抛异常 if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); // Find a power of 2 >= initialCapacity //初始容量为1 ,while循环确保容量为大于initialCapacity的最小的2次方幂 int capacity = 1; while (capacity < initialCapacity) capacity <<= 1; //capacity 左移一位 //设置负载因子 this.loadFactor = loadFactor; //设置临界值 threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); //初始化table table = new Entry[capacity]; useAltHashing = sun.misc.VM.isBooted() && (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD); init(); } /** * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and the default load factor (0.75). * * @param initialCapacity the initial capacity. * @throws IllegalArgumentException if the initial capacity is negative. */ public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { //无参构造器 默认16,负载因子是0.75f this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } /** * Constructs a new <tt>HashMap</tt> with the same mappings as the * specified <tt>Map</tt>. The <tt>HashMap</tt> is created with * default load factor (0.75) and an initial capacity sufficient to * hold the mappings in the specified <tt>Map</tt>. * * @param m the map whose mappings are to be placed in this map * @throws NullPointerException if the specified map is null */ /** * 待补充 */ public HashMap(Map<? extends K, ? extends V> m) { this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR); putAllForCreate(m); }

   2.3 HashMap添加新的<K,V>应用的方法

       2.3.1 put方法

public V put(K key, V value) { //如果key等于null,存储位置为table[0]或table[0]的链表 if (key == null) return putForNullKey(value); //计算hashcode int hash = hash(key); //获取在table中的索引 int i = indexFor(hash, table.length); //在索引i位置上进行遍历,查找到hash值相等并且key相等时,覆盖value值并返回旧的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; } } //修改次数加1 modCount++; //i索引上新增一个entry addEntry(hash, key, value, i); return null; }

      2.3.2 putForNullKey方法

/** * Offloaded version of put for null keys * key为空时调用该方法 */ private V putForNullKey(V value) { //查找哈希表中0索引的位置,是否不为空,如果不为空,则遍历0索引的链表 for (Entry<K,V> e = table[0]; e != null; e = e.next) { //找到key==null的键值,覆盖并返回旧值 if (e.key == null) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } //修改次数加1 modCount++; //添加新entry在哈希表0索引的位置 addEntry(0, null, value, 0); return null; }

      2.3.3 hash函数

hash函数可以将不同的key值输入,得到散列值,但散列值存在相同的情况。当散列值相同时,就会产生冲突,两个值会发生覆盖的可能,即hash冲突,这时需要解决hash冲突的方法,hashmap中使用的便是链地址法

1 开放地址法 1.1 线性探测 1.2 二次探测 1.3 再哈希法 2 链地址法 :在哈希表的每个单元设置链表,数据的key值映射到哈希表的单元,数据项本身插入到链表中 /** * Retrieve object hash code and applies a supplemental hash function to the * result hash, which defends against poor quality hash functions. This is * critical because HashMap uses power-of-two length hash tables, that * otherwise encounter collisions for hashCodes that do not differ * in lower bits. Note: Null keys always map to hash 0, thus index 0. */ final int hash(Object k) { //hash 函数,即散列函数,哈希函数 int h = 0; if (useAltHashing) { if (k instanceof String) { return sun.misc.Hashing.stringHash32((String) k); } h = hashSeed; } 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); }

      2.3.4 indexFor方法

/** * Returns index for hash code h. 计算hashcode的index索引 */ static int indexFor(int h, int length) { /** * HashMap的初始容量和扩容都是以2的次方来进行的,那么length-1换算成二进制的话肯定所有位都 * 为1,就比如2的3次方为8,length-1的二进制表示就是111, 而按位与计算的原则是两位同时 * 为“1”,结果才为“1”,否则为“0”。所以h& (length-1)运算从数值上来讲其实等价于对length取 * 模,也就是h%length。发生碰撞的几率较小 * 计算位与,长度必须是非0的2次方, */ return h & (length-1); }

      2.3.5 addEntry方法和createEntry方法

/** * Adds a new entry with the specified key, value and hash code to * the specified bucket. It is the responsibility of this * method to resize the table if appropriate. * * Subclass overrides this to alter the behavior of put method. */ void addEntry(int hash, K key, V value, int bucketIndex) { //size大于等于临界值threshold并且哈希表索引位置不为空,将table扩容2倍 if ((size >= threshold) && (null != table[bucketIndex])) { resize(2 * table.length); //当key不等于Null时,计算key的hash值,否则hash值为0 hash = (null != key) ? hash(key) : 0; //扩容之后重写计算哈希表的索引 bucketIndex = indexFor(hash, table.length); } //创建新的链表Entry节点 createEntry(hash, key, value, bucketIndex); } /** * Like addEntry except that this version is used when creating entries * as part of Map construction or "pseudo-construction" (cloning, * deserialization). This version needn't worry about resizing the table. * * Subclass overrides this to alter the behavior of HashMap(Map), * clone, and readObject. */ void createEntry(int hash, K key, V value, int bucketIndex) { //创建新的e引用table[bucketIndex]的Entry,之后再创建新的entry,其entry.next指向e,相当于把新的entry插在了头部 Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<>(hash, key, value, e); size++; }

       2.3.6 resize方法: hashmap扩容

单线程情况下,resize是线程安全的,多线程时,线程不安全,有可能会形成循环链表

/** * Rehashes the contents of this map into a new array with a * larger capacity. This method is called automatically when the * number of keys in this map reaches its threshold. * * If current capacity is MAXIMUM_CAPACITY, this method does not * resize the map, but sets threshold to Integer.MAX_VALUE. * This has the effect of preventing future calls. * * @param newCapacity the new capacity, MUST be a power of two; * must be greater than current capacity unless current * capacity is MAXIMUM_CAPACITY (in which case value * is irrelevant). */ void resize(int newCapacity) { //建一个Entry[]数组引用table数据 Entry[] oldTable = table; //获取旧的长度 int oldCapacity = oldTable.length; //当旧的长度达到最大值时,修改阈值为Tnteger的最大值 if (oldCapacity == MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return; } //创建新的Entry数组,使用新的长度 Entry[] newTable = new Entry[newCapacity]; boolean oldAltHashing = useAltHashing; useAltHashing |= sun.misc.VM.isBooted() && (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD); //计算是否要重写hash boolean rehash = oldAltHashing ^ useAltHashing; //将当前哈希表数据复制到新的哈希表 transfer(newTable, rehash); //修改hashmap的table为新的table table = newTable; //修改阈值 threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1); }

       2.3.7 transfer方法:扩容时将当前哈希表数据复制到新的哈希表

/** * Transfers all entries from current table to newTable. */ void transfer(Entry[] newTable, boolean rehash) { //计算容量 int newCapacity = newTable.length; //遍历旧的table表 for (Entry<K,V> e : table) { while(null != e) { Entry<K,V> next = e.next; //entry不为空时,如果要重写hash,则计算hash值 if (rehash) { e.hash = null == e.key ? 0 : hash(e.key); } //定位hash索引位置 int i = indexFor(e.hash, newCapacity); //相当于链表的插入,总是插入在前面,newTable[i]的值为e,之后继续e的下一个元素 e.next = newTable[i]; newTable[i] = e; e = next; } } }

    2.4. HashMap获取<K,V>

      2.4.1 get方法

/** * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * * <p>A return value of {@code null} does not <i>necessarily</i> * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * * @see #put(Object, Object) */ public V get(Object key) { //当key为null时,查找table表0位置的链表,如果找到key为null的则返回该Entry的value,否则返回null if (key == null) return getForNullKey(); Entry<K,V> entry = getEntry(key); return null == entry ? null : entry.getValue(); }

    2.4.2 getForNullKey方法

/** * Offloaded version of get() to look up null keys. Null keys map * to index 0. This null case is split out into separate methods * for the sake of performance in the two most commonly used * operations (get and put), but incorporated with conditionals in * others. */ private V getForNullKey() { //查找table表0位置的链表,如果找到key为null的则返回该Entry的value,否则返回null for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) return e.value; } return null; }

3. JDK8 HashMap

  3.1 JDK7与JDK8的区别

JDK7与JDK8中HashMap实现的最大区别就是对于冲突的处理方法。JDK 1.8 中引入了红黑树(查找时间复杂度为 O(logn)),用数组+链表+红黑树的结构来优化这个问题。当链表长度大于等于8时,则将链表转化为红黑树

HashMap链表和红黑树结构

  3.2 HashMap参数 

/** * The default initial capacity - MUST be a power of two. */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 默认初始化容量 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;//最大的容量大小2^30 /** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认负载因子 /** * The bin count threshold for using a tree rather than list for a * bin. Bins are converted to trees when adding an element to a * bin with at least this many nodes. The value must be greater * than 2 and should be at least 8 to mesh with assumptions in * tree removal about conversion back to plain bins upon * shrinkage. */ static final int TREEIFY_THRESHOLD = 8; //阈值 8,当单个segment的容量超过阈值时,将链表转化为红黑树。 /** * The bin count threshold for untreeifying a (split) bin during a * resize operation. Should be less than TREEIFY_THRESHOLD, and at * most 6 to mesh with shrinkage detection under removal. */ static final int UNTREEIFY_THRESHOLD = 6;//链表化阈值 6。当resize后或者删除操作后单个segment的容量低于阈值时,将红黑树转化为链表。 /** * The smallest table capacity for which bins may be treeified. * (Otherwise the table is resized if too many nodes in a bin.) * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts * between resizing and treeification thresholds. */ static final int MIN_TREEIFY_CAPACITY = 64; //最小树化容量 64。当桶中的bin被树化时最小的hash表容量,低于该容量时不会树化。

  3.3 put函数

流程:

 1. 判断table是否为空或长度等于0,否则resize扩容

 2. 根据键值key计算hash值得到索引i,如果table[i]为空,直接新建node添加,并跳出循环,如果table[i]不为空,进入else判断

 3. 判断table[i]的首个元素是否和key一样,如果相同直接覆盖value,否则转向else if

 4. else if判断是否是红黑树结点,如果是,则新增红黑树结点,否则进入else遍历

 5. 遍历table[i],遍历到链表尾依然为空,则新增链表结点,并判断长度是否大于等于8,是则转换为红黑树,如果遍历过程中找到key值相等的,则覆盖value

 6. 插入成功后判断size是否大于threshold,是则扩容

/** * Implements Map.put and related methods * * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent if true, don't change existing value * @param evict if false, the table is in creation mode. * @return previous value, or null if none */ final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; //判断table是否为空或者length=0,如果是,则进行扩容 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; //hash值与n-1与运算获得索引i,如果i位置为空,则插入新node,否则进入else判断 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; //判断node的hash与key值是否相等,如果相等,则将p赋值给e,(node已存在) if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; //判断是否为红黑树,如果是,直接在红黑树插入键值对 else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //遍历table[i],链表尾部插入新node后,判断binCount是否大于等于7,即长度是否大于等于8,大于8则转化为红黑树 for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } //遍历的时候若找到hash与key都相等,则跳出,进行value覆盖 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } //e不等于null时,代表node已存在,则直接覆盖value,并返回旧值 if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } //修改次数加1 ++modCount; //size大于threshold,进行扩容 if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }

  3.3 hash函数

根据key值计算出hash值,再对32位的hashcode高16位和低16位进行异或,大大减少了哈希冲突

/** * Computes key.hashCode() and spreads (XORs) higher bits of hash * to lower. Because the table uses power-of-two masking, sets of * hashes that vary only in bits above the current mask will * always collide. (Among known examples are sets of Float keys * holding consecutive whole numbers in small tables.) So we * apply a transform that spreads the impact of higher bits * downward. There is a tradeoff between speed, utility, and * quality of bit-spreading. Because many common sets of hashes * are already reasonably distributed (so don't benefit from * spreading), and because we use trees to handle large sets of * collisions in bins, we just XOR some shifted bits in the * cheapest possible way to reduce systematic lossage, as well as * to incorporate impact of the highest bits that would otherwise * never be used in index calculations because of table bounds. */ static final int hash(Object key) { //hash函数,key不为空时,将hashcode右移16位,低16位与高16位进行异或操作,将高位信息存储到低位,目的减少冲突的可能 int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }

  3.4 resize函数

HashMap扩容不需要像JDK1.7重新计算hash,只需要判断原来的hash值新增的那个bit是1还是0,0的话索引没变(因为任何数与0与都依旧是0),bit为1 ,则index变成原索引+oldCap,oldCap为原hashmap的length

final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null) newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = e; loTail = e; } else { if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null); if (loTail != null) { loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }

 

最新回复(0)