哈希表(hash table),也叫散列表,是一种非常重要的数据结构,应用场景及其丰富,许多缓存技术(比如memcached)的核心其实就是在内存中维护一张大的哈希表,本文会对java集合框架中HashMap的实现原理进行讲解,并对JDK7和JDK8的HashMap源码进行分析。

HashMap 在 JDK1.8 之前和之后的区别-图片1

区别

在JDK1.8以前版本中,HashMap的实现是数组+链表,它的缺点是即使哈希函数选择的再好,也很难达到元素百分百均匀分布,而且当HashMap中有大量元素都存到同一个桶中时,这个桶会有一个很长的链表,此时遍历的时间复杂度就是O(n),当然这是最糟糕的情况。

在JDK1.8及以后的版本中引入了红黑树结构,HashMap的实现就变成了数组+链表或数组+红黑树。添加元素时,若桶中链表个数超过8,链表会转换成红黑树;删除元素、扩容时,若桶中结构为红黑树并且树中元素个数较少时会进行修剪或直接还原成链表结构,以提高后续操作性能;遍历、查找时,由于使用红黑树结构,红黑树遍历的时间复杂度为 O(logn),所以性能得到提升。

JDK1.7源码分析

HashMap采用Entry数组来存储key-value对,每一个键值对组成了一个Entry实体,Entry类实际上是一个单向的链表结构,它具有Next指针,可以连接下一个Entry实体,依次来解决Hash冲突的问题,因为HashMap是按照Key的hash值来计算Entry在HashMap中存储的位置的,如果hash值相同,而key内容不相等,那么就用链表来解决这种hash冲突。

  1. package java.util;
  2. import java.io.*;
  3.  
  4. public class HashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable {
  5.  
  6. // 默认初始化的容量
  7. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  8. // 最大的容量
  9. static final int MAXIMUM_CAPACITY = 1 << 30;
  10. // 负载因子,当容量达到75%时就进行扩容操作
  11. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  12. // 当数组还没有进行扩容操作的时候,共享的一个空表对象
  13. static final Entry<?, ?>[] EMPTY_TABLE = {};
  14. // table,进行扩容操作,长度必须2的n次方
  15. transient Entry<K, V>[] table = (Entry<K, V>[]) EMPTY_TABLE;
  16. // Map中包含的元素数量
  17. transient int size;
  18. // 阈值,用于判断是否需要扩容(threshold = 容量*负载因子)
  19. int threshold;
  20. // 加载因子实际的大小
  21. final float loadFactor;
  22. // HashMap改变的次数
  23. transient int modCount;
  24.  
  25. static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
  26.  
  27. // 内部类,通过vm来修改threshold的值
  28. private static class Holder {
  29.  
  30. static final int ALTERNATIVE_HASHING_THRESHOLD;
  31.  
  32. static {
  33. String altThreshold = java.security.AccessController
  34. .doPrivileged(new sun.security.action.GetPropertyAction("jdk.map.althashing.threshold"));
  35.  
  36. int threshold;
  37. try {
  38. threshold = (null != altThreshold) ? Integer.parseInt(altThreshold)
  39. : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;
  40.  
  41. // disable alternative hashing if -1
  42. if (threshold == -1) {
  43. threshold = Integer.MAX_VALUE;
  44. }
  45.  
  46. if (threshold < 0) {
  47. throw new IllegalArgumentException("value must be positive integer.");
  48. }
  49. } catch (IllegalArgumentException failed) {
  50. throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
  51. }
  52.  
  53. ALTERNATIVE_HASHING_THRESHOLD = threshold;
  54. }
  55. }
  56.  
  57. // HashCode的初始值为 0
  58. transient int hashSeed = 0;
  59.  
  60. // 构造方法,指定初始容量和负载因子
  61. public HashMap(int initialCapacity, float loadFactor) {
  62. if (initialCapacity < 0)
  63. throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
  64. if (initialCapacity > MAXIMUM_CAPACITY)
  65. initialCapacity = MAXIMUM_CAPACITY;
  66. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  67. throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
  68.  
  69. this.loadFactor = loadFactor;
  70. threshold = initialCapacity;
  71. init();
  72. }
  73.  
  74. // 构造方法,指定了初始容量
  75. public HashMap(int initialCapacity) {
  76. this(initialCapacity, DEFAULT_LOAD_FACTOR);
  77. }
  78.  
  79. // 无参构造方法,使用默认的容量大小和负载因子,并调用其他的构造方法
  80. public HashMap() {
  81. this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
  82. }
  83.  
  84. // 构造函数,参数为指定的Map集合
  85. public HashMap(Map<? extends K, ? extends V> m) {
  86. this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
  87. inflateTable(threshold);
  88.  
  89. putAllForCreate(m);
  90. }
  91.  
  92. // 选择合适的容量值,最好是number的2的幂数
  93. private static int roundUpToPowerOf2(int number) {
  94. // assert number >= 0 : "number must be non-negative";
  95. return number >= MAXIMUM_CAPACITY ? MAXIMUM_CAPACITY
  96. : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
  97. }
  98.  
  99. // 扩充表,HashMap初始化时是一个空数组,此方法执行重新复制操作,创建一个新的Entry[]
  100. private void inflateTable(int toSize) {
  101. // Find a power of 2 >= toSize
  102. int capacity = roundUpToPowerOf2(toSize);
  103.  
  104. threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
  105. table = new Entry[capacity];
  106. initHashSeedAsNeeded(capacity);
  107. }
  108.  
  109. // internal utilities
  110.  
  111. // 初始化
  112. void init() {
  113. }
  114.  
  115. // 与虚拟机设置有关,改变hashSeed的值
  116. final boolean initHashSeedAsNeeded(int capacity) {
  117. boolean currentAltHashing = hashSeed != 0;
  118. boolean useAltHashing = sun.misc.VM.isBooted() && (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
  119. boolean switching = currentAltHashing ^ useAltHashing;
  120. if (switching) {
  121. hashSeed = useAltHashing ? sun.misc.Hashing.randomHashSeed(this) : 0;
  122. }
  123. return switching;
  124. }
  125.  
  126. // 计算k的hash值
  127. final int hash(Object k) {
  128. int h = hashSeed;
  129. if (0 != h && k instanceof String) {
  130. return sun.misc.Hashing.stringHash32((String) k);
  131. }
  132.  
  133. h ^= k.hashCode();
  134.  
  135. // This function ensures that hashCodes that differ only by
  136. // constant multiples at each bit position have a bounded
  137. // number of collisions (approximately 8 at default load factor).
  138. h ^= (h >>> 20) ^ (h >>> 12);
  139. return h ^ (h >>> 7) ^ (h >>> 4);
  140. }
  141.  
  142. // 根据hashcode,和表的长度,返回存放的索引
  143. static int indexFor(int h, int length) {
  144. // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of
  145. // 2";
  146. return h & (length - 1);
  147. }
  148.  
  149. // 返回Map中键值对的数量
  150. public int size() {
  151. return size;
  152. }
  153.  
  154. // 判断集合是否为空
  155. public boolean isEmpty() {
  156. return size == 0;
  157. }
  158.  
  159. // 返回key对应的值
  160. public V get(Object key) {
  161. if (key == null)
  162. return getForNullKey();
  163. Entry<K, V> entry = getEntry(key);
  164.  
  165. return null == entry ? null : entry.getValue();
  166. }
  167.  
  168. // 返回null键的值
  169. private V getForNullKey() {
  170. if (size == 0) {
  171. return null;
  172. }
  173. for (Entry<K, V> e = table[0]; e != null; e = e.next) {
  174. if (e.key == null)
  175. return e.value;
  176. }
  177. return null;
  178. }
  179.  
  180. // 是否包含键为key的元素
  181. public boolean containsKey(Object key) {
  182. return getEntry(key) != null;
  183. }
  184.  
  185. // 返回键为key的entry实体,不存在返回null
  186. final Entry<K, V> getEntry(Object key) {
  187. if (size == 0) {
  188. return null;
  189. }
  190.  
  191. int hash = (key == null) ? 0 : hash(key);
  192. for (Entry<K, V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
  193. Object k;
  194. if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
  195. return e;
  196. }
  197. return null;
  198. }
  199.  
  200. // 向map中添加key-value 键值对,如果可以包含了key的映射,则旧的value将被替换
  201. public V put(K key, V value) {
  202. if (table == EMPTY_TABLE) {
  203. inflateTable(threshold);
  204. }
  205. if (key == null)
  206. return putForNullKey(value);
  207. int hash = hash(key);
  208. int i = indexFor(hash, table.length);
  209. for (Entry<K, V> e = table[i]; e != null; e = e.next) {
  210. Object k;
  211. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
  212. V oldValue = e.value;
  213. e.value = value;
  214. e.recordAccess(this);
  215. return oldValue;
  216. }
  217. }
  218.  
  219. modCount++;
  220. addEntry(hash, key, value, i);
  221. return null;
  222. }
  223.  
  224. // key = null, 对应的操作,key为null ,存放在entry[]中的0号位置。并用新值替换旧值
  225. private V putForNullKey(V value) {
  226. for (Entry<K, V> e = table[0]; e != null; e = e.next) {
  227. if (e.key == null) {
  228. V oldValue = e.value;
  229. e.value = value;
  230. e.recordAccess(this);
  231. return oldValue;
  232. }
  233. }
  234. modCount++;
  235. addEntry(0, null, value, 0);
  236. return null;
  237. }
  238.  
  239. // 私有方法,添加元素
  240. private void putForCreate(K key, V value) {
  241. int hash = null == key ? 0 : hash(key);
  242. int i = indexFor(hash, table.length);
  243.  
  244. for (Entry<K, V> e = table[i]; e != null; e = e.next) {
  245. Object k;
  246. if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
  247. e.value = value;
  248. return;
  249. }
  250. }
  251.  
  252. createEntry(hash, key, value, i);
  253. }
  254.  
  255. // 将m中的元素添加到HashMap中
  256. private void putAllForCreate(Map<? extends K, ? extends V> m) {
  257. for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
  258. putForCreate(e.getKey(), e.getValue());
  259. }
  260.  
  261. // 扩容操作
  262. void resize(int newCapacity) {
  263. Entry[] oldTable = table;
  264. int oldCapacity = oldTable.length;
  265. if (oldCapacity == MAXIMUM_CAPACITY) {
  266. threshold = Integer.MAX_VALUE;
  267. return;
  268. }
  269.  
  270. Entry[] newTable = new Entry[newCapacity];
  271. transfer(newTable, initHashSeedAsNeeded(newCapacity));
  272. table = newTable;
  273. threshold = (int) Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
  274. }
  275.  
  276. // 将table中的数据复制到newTable中
  277. void transfer(Entry[] newTable, boolean rehash) {
  278. int newCapacity = newTable.length;
  279. for (Entry<K, V> e : table) {
  280. while (null != e) {
  281. Entry<K, V> next = e.next;
  282. if (rehash) {
  283. e.hash = null == e.key ? 0 : hash(e.key);
  284. }
  285. int i = indexFor(e.hash, newCapacity);
  286. e.next = newTable[i];
  287. newTable[i] = e;
  288. e = next;
  289. }
  290. }
  291. }
  292.  
  293. // 将m中的元素全部添加到HashMap中
  294. public void putAll(Map<? extends K, ? extends V> m) {
  295. int numKeysToBeAdded = m.size();
  296. if (numKeysToBeAdded == 0)
  297. return;
  298.  
  299. if (table == EMPTY_TABLE) {
  300. inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
  301. }
  302.  
  303. if (numKeysToBeAdded > threshold) {
  304. int targetCapacity = (int) (numKeysToBeAdded / loadFactor + 1);
  305. if (targetCapacity > MAXIMUM_CAPACITY)
  306. targetCapacity = MAXIMUM_CAPACITY;
  307. int newCapacity = table.length;
  308. while (newCapacity < targetCapacity)
  309. newCapacity <<= 1;
  310. if (newCapacity > table.length)
  311. resize(newCapacity);
  312. }
  313.  
  314. for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
  315. put(e.getKey(), e.getValue());
  316. }
  317.  
  318. // 删除key ,并返回key对应的value值
  319. public V remove(Object key) {
  320. Entry<K, V> e = removeEntryForKey(key);
  321. return (e == null ? null : e.value);
  322. }
  323.  
  324. // 返回key对应的实体
  325. final Entry<K, V> removeEntryForKey(Object key) {
  326. if (size == 0) {
  327. return null;
  328. }
  329. int hash = (key == null) ? 0 : hash(key);
  330. int i = indexFor(hash, table.length);
  331. Entry<K, V> prev = table[i];
  332. Entry<K, V> e = prev;
  333.  
  334. while (e != null) {
  335. Entry<K, V> next = e.next;
  336. Object k;
  337. if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
  338. modCount++;
  339. size--;
  340. if (prev == e)
  341. table[i] = next;
  342. else
  343. prev.next = next;
  344. e.recordRemoval(this);
  345. return e;
  346. }
  347. prev = e;
  348. e = next;
  349. }
  350.  
  351. return e;
  352. }
  353.  
  354. // 删除一个指定的实体
  355. final Entry<K, V> removeMapping(Object o) {
  356. if (size == 0 || !(o instanceof Map.Entry))
  357. return null;
  358.  
  359. Map.Entry<K, V> entry = (Map.Entry<K, V>) o;
  360. Object key = entry.getKey();
  361. int hash = (key == null) ? 0 : hash(key);
  362. int i = indexFor(hash, table.length);
  363. Entry<K, V> prev = table[i];
  364. Entry<K, V> e = prev;
  365.  
  366. while (e != null) {
  367. Entry<K, V> next = e.next;
  368. if (e.hash == hash && e.equals(entry)) {
  369. modCount++;
  370. size--;
  371. if (prev == e)
  372. table[i] = next;
  373. else
  374. prev.next = next;
  375. e.recordRemoval(this);
  376. return e;
  377. }
  378. prev = e;
  379. e = next;
  380. }
  381.  
  382. return e;
  383. }
  384.  
  385. // 删除map
  386. public void clear() {
  387. modCount++;
  388. Arrays.fill(table, null);
  389. size = 0;
  390. }
  391.  
  392. // 判断是否包含指定value的实体
  393. public boolean containsValue(Object value) {
  394. if (value == null)
  395. return containsNullValue();
  396.  
  397. Entry[] tab = table;
  398. for (int i = 0; i < tab.length; i++)
  399. for (Entry e = tab[i]; e != null; e = e.next)
  400. if (value.equals(e.value))
  401. return true;
  402. return false;
  403. }
  404.  
  405. // 是否包含value== null
  406. private boolean containsNullValue() {
  407. Entry[] tab = table;
  408. for (int i = 0; i < tab.length; i++)
  409. for (Entry e = tab[i]; e != null; e = e.next)
  410. if (e.value == null)
  411. return true;
  412. return false;
  413. }
  414.  
  415. // 重写克隆方法
  416. public Object clone() {
  417. HashMap<K, V> result = null;
  418. try {
  419. result = (HashMap<K, V>) super.clone();
  420. } catch (CloneNotSupportedException e) {
  421. // assert false;
  422. }
  423. if (result.table != EMPTY_TABLE) {
  424. result.inflateTable(Math.min((int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
  425. // we have limits...
  426. HashMap.MAXIMUM_CAPACITY), table.length));
  427. }
  428. result.entrySet = null;
  429. result.modCount = 0;
  430. result.size = 0;
  431. result.init();
  432. result.putAllForCreate(this);
  433.  
  434. return result;
  435. }
  436.  
  437. // 静态内部类 ,Entry用来存储键值对,HashMap中的Entry[]用来存储entry
  438. static class Entry<K, V> implements Map.Entry<K, V> {
  439. final K key;
  440. V value;
  441. Entry<K, V> next;
  442. int hash;
  443.  
  444. /**
  445. * Creates new entry.
  446. */
  447. Entry(int h, K k, V v, Entry<K, V> n) {
  448. value = v;
  449. next = n;
  450. key = k;
  451. hash = h;
  452. }
  453.  
  454. public final K getKey() {
  455. return key;
  456. }
  457.  
  458. public final V getValue() {
  459. return value;
  460. }
  461.  
  462. public final V setValue(V newValue) {
  463. V oldValue = value;
  464. value = newValue;
  465. return oldValue;
  466. }
  467.  
  468. public final boolean equals(Object o) {
  469. if (!(o instanceof Map.Entry))
  470. return false;
  471. Map.Entry e = (Map.Entry) o;
  472. Object k1 = getKey();
  473. Object k2 = e.getKey();
  474. if (k1 == k2 || (k1 != null && k1.equals(k2))) {
  475. Object v1 = getValue();
  476. Object v2 = e.getValue();
  477. if (v1 == v2 || (v1 != null && v1.equals(v2)))
  478. return true;
  479. }
  480. return false;
  481. }
  482.  
  483. public final int hashCode() {
  484. return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
  485. }
  486.  
  487. public final String toString() {
  488. return getKey() + "=" + getValue();
  489. }
  490.  
  491. void recordAccess(HashMap<K, V> m) {
  492. }
  493.  
  494. void recordRemoval(HashMap<K, V> m) {
  495. }
  496. }
  497.  
  498. // 添加实体
  499. void addEntry(int hash, K key, V value, int bucketIndex) {
  500. if ((size >= threshold) && (null != table[bucketIndex])) {
  501. resize(2 * table.length);
  502. hash = (null != key) ? hash(key) : 0;
  503. bucketIndex = indexFor(hash, table.length);
  504. }
  505.  
  506. createEntry(hash, key, value, bucketIndex);
  507. }
  508.  
  509. // 创建实体
  510. void createEntry(int hash, K key, V value, int bucketIndex) {
  511. Entry<K, V> e = table[bucketIndex];
  512. table[bucketIndex] = new Entry<>(hash, key, value, e);
  513. size++;
  514. }
  515.  
  516. // 内部类实现Iterator接口,进行遍历操作
  517. private abstract class HashIterator<E> implements Iterator<E> {
  518. Entry<K, V> next; // next entry to return
  519. int expectedModCount; // For fast-fail
  520. int index; // current slot
  521. Entry<K, V> current; // current entry
  522.  
  523. HashIterator() {
  524. expectedModCount = modCount;
  525. if (size > 0) { // advance to first entry
  526. Entry[] t = table;
  527. while (index < t.length && (next = t[index++]) == null)
  528. ;
  529. }
  530. }
  531.  
  532. public final boolean hasNext() {
  533. return next != null;
  534. }
  535.  
  536. final Entry<K, V> nextEntry() {
  537. if (modCount != expectedModCount)
  538. throw new ConcurrentModificationException();
  539. Entry<K, V> e = next;
  540. if (e == null)
  541. throw new NoSuchElementException();
  542.  
  543. if ((next = e.next) == null) {
  544. Entry[] t = table;
  545. while (index < t.length && (next = t[index++]) == null)
  546. ;
  547. }
  548. current = e;
  549. return e;
  550. }
  551.  
  552. public void remove() {
  553. if (current == null)
  554. throw new IllegalStateException();
  555. if (modCount != expectedModCount)
  556. throw new ConcurrentModificationException();
  557. Object k = current.key;
  558. current = null;
  559. HashMap.this.removeEntryForKey(k);
  560. expectedModCount = modCount;
  561. }
  562. }
  563.  
  564. private final class ValueIterator extends HashIterator<V> {
  565. public V next() {
  566. return nextEntry().value;
  567. }
  568. }
  569.  
  570. private final class KeyIterator extends HashIterator<K> {
  571. public K next() {
  572. return nextEntry().getKey();
  573. }
  574. }
  575.  
  576. private final class EntryIterator extends HashIterator<Map.Entry<K, V>> {
  577. public Map.Entry<K, V> next() {
  578. return nextEntry();
  579. }
  580. }
  581.  
  582. // Subclass overrides these to alter behavior of views' iterator() method
  583. Iterator<K> newKeyIterator() {
  584. return new KeyIterator();
  585. }
  586.  
  587. Iterator<V> newValueIterator() {
  588. return new ValueIterator();
  589. }
  590.  
  591. Iterator<Map.Entry<K, V>> newEntryIterator() {
  592. return new EntryIterator();
  593. }
  594.  
  595. // Views
  596.  
  597. private transient Set<Map.Entry<K, V>> entrySet = null;
  598.  
  599. public Set<K> keySet() {
  600. Set<K> ks = keySet;
  601. return (ks != null ? ks : (keySet = new KeySet()));
  602. }
  603.  
  604. private final class KeySet extends AbstractSet<K> {
  605. public Iterator<K> iterator() {
  606. return newKeyIterator();
  607. }
  608.  
  609. public int size() {
  610. return size;
  611. }
  612.  
  613. public boolean contains(Object o) {
  614. return containsKey(o);
  615. }
  616.  
  617. public boolean remove(Object o) {
  618. return HashMap.this.removeEntryForKey(o) != null;
  619. }
  620.  
  621. public void clear() {
  622. HashMap.this.clear();
  623. }
  624. }
  625.  
  626. public Collection<V> values() {
  627. Collection<V> vs = values;
  628. return (vs != null ? vs : (values = new Values()));
  629. }
  630.  
  631. private final class Values extends AbstractCollection<V> {
  632. public Iterator<V> iterator() {
  633. return newValueIterator();
  634. }
  635.  
  636. public int size() {
  637. return size;
  638. }
  639.  
  640. public boolean contains(Object o) {
  641. return containsValue(o);
  642. }
  643.  
  644. public void clear() {
  645. HashMap.this.clear();
  646. }
  647. }
  648.  
  649. public Set<Map.Entry<K, V>> entrySet() {
  650. return entrySet0();
  651. }
  652.  
  653. private Set<Map.Entry<K, V>> entrySet0() {
  654. Set<Map.Entry<K, V>> es = entrySet;
  655. return es != null ? es : (entrySet = new EntrySet());
  656. }
  657.  
  658. private final class EntrySet extends AbstractSet<Map.Entry<K, V>> {
  659. public Iterator<Map.Entry<K, V>> iterator() {
  660. return newEntryIterator();
  661. }
  662.  
  663. public boolean contains(Object o) {
  664. if (!(o instanceof Map.Entry))
  665. return false;
  666. Map.Entry<K, V> e = (Map.Entry<K, V>) o;
  667. Entry<K, V> candidate = getEntry(e.getKey());
  668. return candidate != null && candidate.equals(e);
  669. }
  670.  
  671. public boolean remove(Object o) {
  672. return removeMapping(o) != null;
  673. }
  674.  
  675. public int size() {
  676. return size;
  677. }
  678.  
  679. public void clear() {
  680. HashMap.this.clear();
  681. }
  682. }
  683.  
  684. // 将对象写入到输出流中
  685. private void writeObject(java.io.ObjectOutputStream s) throws IOException {
  686. // Write out the threshold, loadfactor, and any hidden stuff
  687. s.defaultWriteObject();
  688.  
  689. // Write out number of buckets
  690. if (table == EMPTY_TABLE) {
  691. s.writeInt(roundUpToPowerOf2(threshold));
  692. } else {
  693. s.writeInt(table.length);
  694. }
  695.  
  696. // Write out size (number of Mappings)
  697. s.writeInt(size);
  698.  
  699. // Write out keys and values (alternating)
  700. if (size > 0) {
  701. for (Map.Entry<K, V> e : entrySet0()) {
  702. s.writeObject(e.getKey());
  703. s.writeObject(e.getValue());
  704. }
  705. }
  706. }
  707.  
  708. private static final long serialVersionUID = 362498820763181265L;
  709.  
  710. // 从输入流中读取对象
  711. private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
  712. // Read in the threshold (ignored), loadfactor, and any hidden stuff
  713. s.defaultReadObject();
  714. if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
  715. throw new InvalidObjectException("Illegal load factor: " + loadFactor);
  716. }
  717.  
  718. // set other fields that need values
  719. table = (Entry<K, V>[]) EMPTY_TABLE;
  720.  
  721. // Read in number of buckets
  722. s.readInt(); // ignored.
  723.  
  724. // Read number of mappings
  725. int mappings = s.readInt();
  726. if (mappings < 0)
  727. throw new InvalidObjectException("Illegal mappings count: " + mappings);
  728.  
  729. // capacity chosen by number of mappings and desired load (if >= 0.25)
  730. int capacity = (int) Math.min(mappings * Math.min(1 / loadFactor, 4.0f),
  731. // we have limits...
  732. HashMap.MAXIMUM_CAPACITY);
  733.  
  734. // allocate the bucket array;
  735. if (mappings > 0) {
  736. inflateTable(capacity);
  737. } else {
  738. threshold = capacity;
  739. }
  740.  
  741. init(); // Give subclass a chance to do its thing.
  742.  
  743. // Read the keys and values, and put the mappings in the HashMap
  744. for (int i = 0; i < mappings; i++) {
  745. K key = (K) s.readObject();
  746. V value = (V) s.readObject();
  747. putForCreate(key, value);
  748. }
  749. }
  750.  
  751. // These methods are used when serializing HashSets
  752. int capacity() {
  753. return table.length;
  754. }
  755.  
  756. float loadFactor() {
  757. return loadFactor;
  758. }
  759. }

重要方法深度解析

构造方法

  1. HashMap() //无参构造方法
  2. HashMap(int initialCapacity) //指定初始容量的构造方法
  3. HashMap(int initialCapacity, float loadFactor) //指定初始容量和负载因子
  4. HashMap(Map<? extends K,? extends V> m) //指定集合,转化为HashMap

HashMap提供了四个构造方法,构造方法中 ,依靠第三个方法来执行的,但是前三个方法都没有进行数组的初始化操作,即使调用了构造方法,此时存放HaspMap中数组元素的table表长度依旧为0 。在第四个构造方法中调用了inflateTable()方法完成了table的初始化操作,并将m中的元素添加到HashMap中。

添加方法

  1. public V put(K key, V value) {
  2. if (table == EMPTY_TABLE) {
  3. inflateTable(threshold);
  4. }
  5. if (key == null)
  6. return putForNullKey(value);
  7. int hash = hash(key);
  8. int i = indexFor(hash, table.length);
  9. for (Entry<K,V> e = table[i]; e != null; e = e.next) {
  10. Object k;
  11. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
  12. V oldValue = e.value;
  13. e.value = value;
  14. e.recordAccess(this);
  15. return oldValue;
  16. }
  17. }
  18.  
  19. modCount++;
  20. addEntry(hash, key, value, i);
  21. return null;
  22. }

在该方法中,添加键值对时,首先进行table是否初始化的判断,如果没有进行初始化(分配空间,Entry[]数组的长度)。然后进行key是否为null的判断,如果key==null ,放置在Entry[]的0号位置。计算在Entry[]数组的存储位置,判断该位置上是否已有元素,如果已经有元素存在,则遍历该Entry[]数组位置上的单链表。判断key是否存在,如果key已经存在,则用新的value值,替换点旧的value值,并将旧的value值返回。如果key不存在于HashMap中,程序继续向下执行。将key-vlaue, 生成Entry实体,添加到HashMap中的Entry[]数组中。

addEntry()

  1. void addEntry(int hash, K key, V value, int bucketIndex) {
  2. if ((size >= threshold) && (null != table[bucketIndex])) {
  3. resize(2 * table.length);
  4. hash = (null != key) ? hash(key) : 0;
  5. bucketIndex = indexFor(hash, table.length);
  6. }
  7.  
  8. createEntry(hash, key, value, bucketIndex);
  9. }
  10.  
  11. void createEntry(int hash, K key, V value, int bucketIndex) {
  12. Entry<K,V> e = table[bucketIndex];
  13. table[bucketIndex] = new Entry<>(hash, key, value, e);
  14. size++;
  15. }

添加方法的具体操作,在添加之前先进行容量的判断,如果当前容量达到了阈值,并且需要存储到Entry[]数组中,先进行扩容操作,扩充的容量为table长度的2倍。重新计算hash值,和数组存储的位置,扩容后的链表顺序与扩容前的链表顺序相反。然后将新添加的Entry实体存放到当前Entry[]位置链表的头部。
在1.8之前,新插入的元素都是放在了链表的头部位置,但是这种操作在高并发的环境下容易导致死锁,所以1.8之后,新插入的元素都放在了链表的尾部。

获取方法

  1. public V get(Object key) {
  2. if (key == null)
  3. return getForNullKey();
  4. Entry<K,V> entry = getEntry(key);
  5.  
  6. return null == entry ? null : entry.getValue();
  7. }
  8.  
  9. final Entry<K,V> getEntry(Object key) {
  10. if (size == 0) {
  11. return null;
  12. }
  13.  
  14. int hash = (key == null) ? 0 : hash(key);
  15. for (Entry<K,V> e = table[indexFor(hash, table.length)];
  16. e != null;
  17. e = e.next) {
  18. Object k;
  19. if (e.hash == hash &&
  20. ((k = e.key) == key || (key != null && key.equals(k))))
  21. return e;
  22. }
  23. return null;
  24. }

在get方法中,首先计算hash值,然后调用indexFor()方法得到该key在table中的存储位置,得到该位置的单链表,遍历列表找到key和指定key内容相等的Entry,返回entry.value值。

删除方法

  1. public V remove(Object key) {
  2. Entry<K,V> e = removeEntryForKey(key);
  3. return (e == null ? null : e.value);
  4. }
  5.  
  6. final Entry<K,V> removeEntryForKey(Object key) {
  7. if (size == 0) {
  8. return null;
  9. }
  10. int hash = (key == null) ? 0 : hash(key);
  11. int i = indexFor(hash, table.length);
  12. Entry<K,V> prev = table[i];
  13. Entry<K,V> e = prev;
  14.  
  15. while (e != null) {
  16. Entry<K,V> next = e.next;
  17. Object k;
  18. if (e.hash == hash &&
  19. ((k = e.key) == key || (key != null && key.equals(k)))) {
  20. modCount++;
  21. size--;
  22. if (prev == e)
  23. table[i] = next;
  24. else
  25. prev.next = next;
  26. e.recordRemoval(this);
  27. return e;
  28. }
  29. prev = e;
  30. e = next;
  31. }
  32.  
  33. return e;
  34. }

删除操作,先计算指定key的hash值,然后计算出table中的存储位置,判断当前位置是否Entry实体存在,如果没有直接返回,若当前位置有Entry实体存在,则开始遍历列表。定义了三个Entry引用,分别为pre, e ,next。 在循环遍历的过程中,首先判断pre 和 e 是否相等,若相等表明,table的当前位置只有一个元素,直接将table[i] = next = null 。若形成了pre -> e -> next 的连接关系,判断e的key是否和指定的key 相等,若相等则让pre -> next ,e 失去引用。

JDK 1.8的 改变

在Jdk1.8中HashMap的实现方式做了一些改变,但是基本思想还是没有变得,只是在一些地方做了优化,下面来看一下这些改变的地方,数据结构的存储由数组+链表的方式,变化为数组+链表+红黑树的存储方式,在性能上进一步得到提升。

数据存储方式

HashMap 在 JDK1.8 之前和之后的区别-图片2

put方法简单解析

  1. public V put(K key, V value) {
  2. return putVal(hash(key), key, value, false, true);
  3. }
  4.  
  5. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
  6. boolean evict) {
  7. Node<K,V>[] tab; Node<K,V> p; int n, i;
  8. if ((tab = table) == null || (n = tab.length) == 0)
  9. n = (tab = resize()).length;
  10. if ((p = tab[i = (n - 1) & hash]) == null)
  11. tab[i] = newNode(hash, key, value, null);
  12. else {
  13. Node<K,V> e; K k;
  14. if (p.hash == hash &&
  15. ((k = p.key) == key || (key != null && key.equals(k))))
  16. e = p;
  17. else if (p instanceof TreeNode)
  18. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  19. else {
  20. for (int binCount = 0; ; ++binCount) {
  21. if ((e = p.next) == null) {
  22. p.next = newNode(hash, key, value, null);
  23. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  24. treeifyBin(tab, hash);
  25. break;
  26. }
  27. if (e.hash == hash &&
  28. ((k = e.key) == key || (key != null && key.equals(k))))
  29. break;
  30. p = e;
  31. }
  32. }
  33. if (e != null) { // existing mapping for key
  34. V oldValue = e.value;
  35. if (!onlyIfAbsent || oldValue == null)
  36. e.value = value;
  37. afterNodeAccess(e);
  38. return oldValue;
  39. }
  40. }
  41. ++modCount;
  42. if (++size > threshold)
  43. resize();
  44. afterNodeInsertion(evict);
  45. return null;
  46. }

get方法简单解析

  1. public V get(Object key) {
  2. Node<K,V> e;
  3. return (e = getNode(hash(key), key)) == null ? null : e.value;
  4. }
  5.  
  6. final Node<K,V> getNode(int hash, Object key) {
  7. Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
  8. if ((tab = table) != null && (n = tab.length) > 0 &&
  9. (first = tab[(n - 1) & hash]) != null) {
  10. if (first.hash == hash && // always check first node
  11. ((k = first.key) == key || (key != null && key.equals(k))))
  12. return first;
  13. if ((e = first.next) != null) {
  14. if (first instanceof TreeNode)
  15. return ((TreeNode<K,V>)first).getTreeNode(hash, key);
  16. do {
  17. if (e.hash == hash &&
  18. ((k = e.key) == key || (key != null && key.equals(k))))
  19. return e;
  20. } while ((e = e.next) != null);
  21. }
  22. }
  23. return null;
  24. }

总结

HashMap采用hash算法来决定Map中key的存储,并通过hash算法来增加集合的大小。
hash表里可以存储元素的位置称为桶(bucket),如果通过key计算hash值发生冲突时,那么将采用链表的形式,来存储元素。
HashMap的扩容操作是一项很耗时的任务,所以如果能估算Map的容量,最好给它一个默认初始值,避免进行多次扩容。
HashMap的线程是不安全的,多线程环境中推荐是ConcurrentHashMap。

本文已通过「原本」原创作品认证,转载请注明文章出处及链接。

Java最后更新:2022-11-6
夏日阳光
  • 本文由 夏日阳光 发表于 2019年10月14日
  • 本文为夏日阳光原创文章,转载请务必保留本文链接:https://www.pieruo.com/115.html
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定

拖动滑块以完成验证
加载中...