1.HashMap的简介 (JDK1.7.0_79版本)

HashMap是基于哈希表的Map实现的的,一个Key对应一个Value,允许使用null键和null值,不保证映射的顺序,特别是它不保证该顺序恒久不变!也不是同步的。

怎么理解不保证恒久不变呢?

当哈希表中的条目数超出了加载因子与当前容量的乘积时的时候,哈希表进行rehash操作(即重建内部数据结构),此时映射顺序可能会被打乱!

HashMap存放元素是通过哈希算法将其中的元素散列的存放在各个“桶”之间。

注:HashMap除了非同步和可以使用null之外,其他的和HashTable大致相同。so ,后面就不在介绍HashTable了!

2.HashMap的继承关系

  1. HashMap<K,V>
  2. java.lang.Object
  3. 继承者 java.util.AbstractMap<K,V>
  4. 继承者 java.util.HashMap<K,V>
  5. 类型参数:
  6. K - 此映射所维护的键的类型
  7. V - 所映射值的类型
  8. 所有已实现的接口:
  9. Serializable, Cloneable, Map<K,V>
  • 继承AbstractMap 抽象类, AbstractMap实现了Map接口中的一些方法,减少了重复代码!

  • 实现了Map、Cloneable、java.io.Serializable接口!

类图关系参看上一篇的Map介绍

3.HashMap的API

HashMap API

(1)构造函数:

  1. HashMap()
  2. 构造一个具有默认初始容量 (16) 和默认加载因子 (0.75) 的空 HashMap
  3. HashMap(int initialCapacity)
  4. 构造一个带指定初始容量和默认加载因子 (0.75) 的空 HashMap
  5. HashMap(int initialCapacity, float loadFactor)
  6. 构造一个带指定初始容量和加载因子的空 HashMap
  7. HashMap(Map<? extends K,? extends V> m)
  8. 构造一个映射关系与指定 Map 相同的新 HashMap

(2)方法

  1. void clear()
  2. 从此映射中移除所有映射关系。
  3. Object clone()
  4. 返回此 HashMap 实例的浅表副本:并不复制键和值本身。
  5. boolean containsKey(Object key)
  6. 如果此映射包含对于指定键的映射关系,则返回 true
  7. boolean containsValue(Object value)
  8. 如果此映射将一个或多个键映射到指定值,则返回 true
  9. Set<Map.Entry<K,V>> entrySet()
  10. 返回此映射所包含的映射关系的 Set 视图。
  11. V get(Object key)
  12. 返回指定键所映射的值;如果对于该键来说,此映射不包含任何映射关系,则返回 null
  13. boolean isEmpty()
  14. 如果此映射不包含键-值映射关系,则返回 true
  15. Set<K> keySet()
  16. 返回此映射中所包含的键的 Set 视图。
  17. V put(K key, V value)
  18. 在此映射中关联指定值与指定键。
  19. void putAll(Map<? extends K,? extends V> m)
  20. 将指定映射的所有映射关系复制到此映射中,这些映射关系将替换此映射目前针对指定映射中所有键的所有映射关系。
  21. V remove(Object key)
  22. 从此映射中移除指定键的映射关系(如果存在)。
  23. int size()
  24. 返回此映射中的键-值映射关系数。
  25. Collection<V> values()
  26. 返回此映射所包含的值的 Collection 视图。

从类 java.util.AbstractMap 继承的方法

equals, hashCode, toString !

4.源码


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

5.总结

(1):HashMap是通过哈希表来存储一个key-value的键值对,每个key对应一个value,允许key和value为null! hash

(2):HashMap 的实例有两个参数影响其性能:初始容量 和加载因子。容量是哈希表中桶的数量,初始容量只是哈希表在创建时的容量。HashMap的容量不足的时候,可以自动扩容resize(),但是最大容量为MAXIMUM_CAPACITY==2^30!

(3):put和get都是分为null和非null进行判断!

(4):resize非常耗时的操作,因此,我们在用HashMap的时,最好能提前预估下HashMap中元素的个数,这样有助于提高HashMap的性能。

(5):求hash值和索引值的方法,这两个方法便是HashMap设计的最为核心的部分,二者结合能保证哈希表中的元素尽可能均匀地散列。

引用:

HashMap中则通过h&(length-1)的方法来代替取模,同样实现了均匀的散列,但效率要高很多,这也是HashMap对Hashtable的一个改进。
接下来,我们分析下为什么哈希表的容量一定要是2的整数次幂。
首先,length为2的整数次幂的话,h&(length-1)就相当于对length取模,这样便保证了散列的均匀,同时也提升了效率;
其次,length为2的整数次幂的话,为偶数,这样length-1为奇数,奇数的最后一位是1,这样便保证了h&(length-1)的最后一位可能为0,也可能为1(这取决于h的值),即与后的结果可能为偶数,也可能为奇数,
这样便可以保证散列的均匀性,而如果length为奇数的话,很明显length-1为偶数,它的最后一位是0,这样h&(length-1)的最后一位肯定为0,即只能为偶数,这样任何hash值都只会被散列到数组的偶数下标位置上,这便浪费了近一半的空间,
因此,length取2的整数次幂,是为了使不同hash值发生碰撞的概率较小,这样就能使元素在哈希表中均匀地散列。

参考文章:

HashMap源码剖析:http://blog.csdn.net/ns_code/article/details/36034955

附:

JDK8中HashMap的底层实现:http://ericchunli.iteye.com/blog/2356721


欢迎访问我的csdn博客,我们一同成长!

"不管做什么,只要坚持下去就会看到不一样!在路上,不卑不亢!"

博客首页:http://blog.csdn.net/u010648555

java集合系列——Map之HashMap介绍(八)的更多相关文章

  1. java集合系列——Map之TreeMap介绍(九)

    一.TreeMap的简介 TreeMap是一个有序的key-value集合,基于红黑树(Red-Black tree)的 NavigableMap实现.该映射根据其键的自然顺序进行排序,或者根据创建映 ...

  2. Java 集合系列10之 HashMap详细介绍(源码解析)和使用示例

    概要 这一章,我们对HashMap进行学习.我们先对HashMap有个整体认识,然后再学习它的源码,最后再通过实例来学会使用HashMap.内容包括:第1部分 HashMap介绍第2部分 HashMa ...

  3. Java 集合系列 10 Hashtable详细介绍(源码解析)和使用示例

    java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...

  4. Java 集合系列 06 Stack详细介绍(源码解析)和使用示例

    java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...

  5. Java 集合系列 05 Vector详细介绍(源码解析)和使用示例

    java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...

  6. Java 集合系列 04 LinkedList详细介绍(源码解析)和使用示例

    java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...

  7. Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例

    java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...

  8. 【转】Java 集合系列10之 HashMap详细介绍(源码解析)和使用示例

    概要 这一章,我们对HashMap进行学习.我们先对HashMap有个整体认识,然后再学习它的源码,最后再通过实例来学会使用HashMap.内容包括:第1部分 HashMap介绍第2部分 HashMa ...

  9. Java集合系列(四):HashMap、Hashtable、LinkedHashMap、TreeMap的使用方法及区别

    本篇博客主要讲解Map接口的4个实现类HashMap.Hashtable.LinkedHashMap.TreeMap的使用方法以及三者之间的区别. 注意:本文中代码使用的JDK版本为1.8.0_191 ...

随机推荐

  1. hdu4746 Mophues

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4746 题意:给出n, m, p,求有多少对a, b满足gcd(a, b)的素因子个数<=p,(其 ...

  2. Nginx学习之HTTP/2.0配置

    哎呀,一不小心自己的博客也是HTTP/2.0了,前段时间对网站进行了https迁移并上了CDN,最终的结果是这酱紫的(重点小绿锁,安全标示以及HTTP/2.0请求). 科普 随着互联网的快速发展,HT ...

  3. POI 自用API

    poi包下载 API 使用POI生成Excel,大家都是赞个.可是狐狸觉得毕竟不是微软的产品,使用没有C#语言的好用,方法还是存在极限的. 下面总结狐狸自己用过的方法: import org.apac ...

  4. spring整合mybatis错误:Caused by: org.xml.sax.SAXParseException; lineNumber: 5; columnNumber: 62; 文档根元素 "mapper" 必须匹配 DOCTYPE 根 "configuration"。

    运行环境:jdk1.7.0_17+tomcat 7 + spring:3.2.0 +mybatis:3.2.7+ eclipse 错误:Caused by: org.xml.sax.SAXParseE ...

  5. JSONP的实现流程

    在进行AJAX的时候会经常产生这样一个报错: 看红字,这是浏览器的同源策略,使跨域进行的AJAX无效.注意,不是不发送AJAX请求(其实就是HTTP请求),而是请求了,也返回了,但浏览器‘咔擦’一声, ...

  6. IPsec_VPN实现技术【转载】

    GRE Tunnel GRE Tunnel(General Routing Encapsulation 通用路由封装)是一种非常简单的VPN(Virtual Private Network 虚拟专用网 ...

  7. [转载]dreamweaver代码提示失效

    原文地址:dreamweaver代码提示失效作者:云中雁 2007-03-23 12:19:22|  分类: 编程手记 |  标签:web2.0  javascript   |字号大中小 订阅 吴庆民 ...

  8. java aio nio bio

    转自:http://blog.csdn.NET/liuxiao723846/article/details/45066095 Java中的IO主要源自于网络和本地文件 IO的方式通常分为几种,同步阻塞 ...

  9. 2D命令行小游戏Beta1.0

    前提: 遇到许多问题,没有参考大佬一些方法是敲不出来的...Orz using System; using System.Collections.Generic; using System.Linq; ...

  10. 团队作业4——第一次项目冲刺 tHiRd DaY

    项目冲刺--Triple Kill 小编又来了,好困呐,上了一天的课还要写博客,为什么写博客的一直是我呢..一点乐子都没有*-* 但是我还是得写啊[我也很无奈啊],那就让我给大家找点乐子吧 天霸动霸. ...