本文为jdk1.8源码。跟1.7最大的区别是引入了红黑树。1.8之前HashMap的数据结构为【数组-链表】 1.8之后增加了【数组-红黑树】默认在链表大于8时,转为红黑树结构
-
【默认值】初始化容量
/** * 初始化容量。16 * The default initial capacity - MUST be a power of two. */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 ```
-
【默认值】扩容启动默认值 在占到0.75的容量时,扩容.即3/4。扩容数量为2倍,在put()方法中新的value插入完成后,进行是否扩容的判断
/** * 在占到0.75的容量时,扩容.即3/4。扩容数量为2倍 * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f;
-
【默认值】链表长度超过8时,转为红黑树,小于等于6时,降为链表
static final int TREEIFY_THRESHOLD = 8; static final int UNTREEIFY_THRESHOLD = 6;
-
【方法】有构造方法设置自定义的初始容量和扩容方案
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; this.threshold = tableSizeFor(initialCapacity); }
-
【方法】put(Key,Value) 最常用的方法 它有返回值。 可以发现,在key存在的情况下返回的是老的value,如果key不存在,则返回null 。 put方法是jdk1.8中改动最大的,多了一个putVal()方法。里面增加了红黑数(TreeNode)的数据结构,HashMap的查询速度得到了提升
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } /** * Implements Map.put and related methods * * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent 如果为true 不改变已存在key的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) { /** * 这里可以看到HashMap的数据结构:tab 为数组。里面存着Node(链表或红黑树) */ Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; /** * hash值即为数组的index */ if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; /** * 判断table[i] 是否为treeNode,即table[i] 是否是红黑树, * 如果是红黑树,则直接在树中插入键值对 */ else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { /** * 遍历table[i],判断链表长度是否大于TREEIFY_THRESHOLD(默认值为8),大于8的话把链表转换为红黑树, * 在红黑树中执行插入操作,否则进行链表的插入操作;遍历过程中若发现key已经存在直接覆盖value即可; */ for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { /** * 对上一个Node的next 参数赋值为当前的Node,链式得到建立 */ p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } /** * 可以发现,在key存在的情况下返回的是老的value */ if (e != null) { // existing mapping for key /** *value值不会被覆盖,只是做了交换,老的值要返回 */ V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; /** * 插入成功后,判断实际存在的键值对数量size是否超多了最大容量threshold, * 如果超过,进行扩容 */ if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
-
【内部类】Node<K,V> 链表和红黑树结构。jdk1.8之前。这个实体叫 Entry
static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; /** * 下一个Node存储在next中,实现了链式结构 */ Node<K,V> next; Node(int hash, K key, V value, Node<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } }
- 【方法】resize() 容量调整方法
/** * Initializes or doubles table size. If null, allocates in * accord with initial capacity target held in field threshold. * Otherwise, because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move * with a power of two offset in the new table. * * @return the table */ 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; } /** *当前容量*2后小于最大容量,并大于默认初始化容量(8)时, *进行扩容,扩容为2倍 */ else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold 扩容为2倍 } 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; /** * 存在树结构时,判断是否需要降为链表。 *默认UNTREEIFY_THRESHOLD=6 小于等于6时降为链表 */ 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; }
- 【方法】提高遍历效率: entrySet() 方法返回entry集合,在对Map做遍历时,经常忽视这个entrySet(), 大部分时候使用的是keySet()方法,这个集合只返回了key,要取value的话需要再调用get(),这次调用就浪费了资源
public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es; return (es = entrySet) == null ? (entrySet = new EntrySet()) : es; }