Konglx +

HashMap

HashMap的实现原理

1.概述

HashMap是基于哈希表的Map接口的非同步实现。此实现提供所有可选的映射操作,并允许使用null值和null键。此类不保证映射的顺序,特别是它不保证该顺序恒久不变。

2.数据结构

要理解HashMap, 就必须要知道了解其底层的实现, 而底层实现里最重要的就是它的数据结构了,HashMap实际上是一个“链表散列”的数据结构,即数组和链表的结合体。
客官请看图: 数组-链表-HashMap

  1. /**
  2. * The table, initialized on first use, and resized as
  3. * necessary. When allocated, length is always a power of two.
  4. * (We also tolerate length zero in some operations to allow
  5. * bootstrapping mechanics that are currently not needed.)
  6. */
  7. transient Node<K,V>[] table;
  8. /**
  9. * Holds cached entrySet(). Note that AbstractMap fields are used
  10. * for keySet() and values().
  11. */
  12. transient Set<Map.Entry<K,V>> entrySet;

这是HashMap最为主要的声明, table是一个包含Node键值对的数组, Node是HashMap实现的一个内部类, 下面是该类的完整实现。

  1. /**
  2. * Basic hash bin node, used for most entries. (See below for
  3. * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
  4. */
  5. static class Node<K,V> implements Map.Entry<K,V> {
  6. final int hash;
  7. final K key;
  8. V value;
  9. Node<K,V> next;
  10. Node(int hash, K key, V value, Node<K,V> next) {
  11. this.hash = hash;
  12. this.key = key;
  13. this.value = value;
  14. this.next = next;
  15. }
  16. public final K getKey() { return key; }
  17. public final V getValue() { return value; }
  18. public final String toString() { return key + "=" + value; }
  19. public final int hashCode() {
  20. return Objects.hashCode(key) ^ Objects.hashCode(value);
  21. }
  22. public final V setValue(V newValue) {
  23. V oldValue = value;
  24. value = newValue;
  25. return oldValue;
  26. }
  27. public final boolean equals(Object o) {
  28. if (o == this)
  29. return true;
  30. if (o instanceof Map.Entry) {
  31. Map.Entry<?,?> e = (Map.Entry<?,?>)o;
  32. if (Objects.equals(key, e.getKey()) &&
  33. Objects.equals(value, e.getValue()))
  34. return true;
  35. }
  36. return false;
  37. }

其中有几个方法挺有意思的, 比如hashCode()的计算是等于键和值的hashCode的按位取反,equals()方法中只有当key 和value同时相等时该Node才相等。


深入Java集合学习系列:HashMap的实现原理

Blog

Opinion

Project