JDK源码分析-——图解版——HashMap

一图胜千言:最好结合源码对照看理解执行原理: 

 对应HashMap 核心源代码:

 

 

 

需要注意的几个关键点 :

  • 1.HashMap 实现了Map所有的操作,允许null作为 key/value;无序(因为h&length-1,也就是bucket数组索引无序)

  • 2.HashMap 除了非同步安全性,k\v 允许null, HashTable与之相反,为线程安全(但效率不如ConcurrentHashMap),key与value都不允许null值。

  • 3.两个因素影响HashMap性能:”initial capacity”、”load factor” . threshold=(capacity * load factor),当size超过threshold,会产生rehash

  • initial capacity:is the number of buckets in the hash table

  • load factor :is a measure of how full the hash table is allowed toget before its capacity is automatically increased

  • 4.当HashMap中的entry超过了,capacity(.75 defautl,更高的值导致 空间占用-,检索耗时+)与loadFactor的计算值,rehashed(内部数据结构重新构建) twice the number of buckets.

  • 5.HashMap是非同步的,如果多个线程访问这个HashMap,至少其中有一个对这个HashMap做了结构修改(add\remove),那必须在外部完成“同步”!一般使用Collections.synchronized(new Hash())

  • 6.Fail-fast iterators:当你从HashMap中遍历出来的 一个对象,然后这个HashMap结构变化,这个对象会fail-fast立即失效(throw ConcurrentModificationException).除非你使用Iterator.remove

猜你喜欢

转载自blog.csdn.net/Coder_Boy_/article/details/106797622