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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章