Java幾種Map:
1. TreeMap。TreeMap實現SortMap,底層是紅黑樹實現,能夠快速查詢,可是每次插入和刪除須要花費時間,由於TreeMap是根據鍵值排好序的;
2. HashMap。HashMap底層是Hash表實現,HashMap容許一個鍵值爲null,容許多個值爲null,插入、刪除和查找元素,HashMap是最好的選擇,HashMap遍歷速度和容量有關;
3. LinkedHashMap。LinkedHashMap是HashMap子類,保存了記錄插入的順序,LinkedHashMap遍歷速度和實際數據有關;
4. WeakHashMap。WeakHashMap弱引用HashMap,當鍵值除了自身引用外沒有其餘地方時,調用系統gc並訪問鍵值時,WeakHashMap就會拋棄這個元素;
5. ConcurrentHashMap。ConcurrentHashMap支持線程同步(鎖住一個桶);
6. Hashtable。Hashtable繼承Dictionary,支持線程同步(鎖住整張表),不容許記錄的鍵值和值爲null,hashcode直接使用object的hashcode。
對比:
TreeMap和HashMap相比,TreeMap實現了排序,當對順序有要求是能夠使用TreeMap,可是TreeMap在插入、刪除和查詢上性能都不如HashMap,因此沒有順序要求時,優先考慮使用HashMap。
HashMap和LinkedHashMap對比,通常狀況下HashMap遍歷速度比LinkedHashMap快,當HashMap容量很大實際數據不多時,LinkedHashMap可能比HashMap快,由於容量會影響HashMap的遍歷速度,而LinkedHashMap遍歷只受實際數據影響。
ConcurrentHashMap和Hashtable。ConcurrentHashMap和Hashtable都支持線程安全,可是Hashtable是用synchronized鎖住整張表,ConcurrentHashMap是分段鎖之鎖住一個桶,因此ConcurrentHashMap的性能要比Hashtable高。安全