1. 程式人生 > >HashMap,LinkedHashMap,TreeMap區別

HashMap,LinkedHashMap,TreeMap區別

注:去年專案有用到LinkedHashMap,最開始忘記這個,浪費了點時間,剛好看到阿里開發手冊,記錄一下區別。

HashMap

最多隻允許一條記錄的鍵為Null;允許多條記錄的值為 Null

非執行緒安全

LinkedHashMap

儲存了記錄的插入順序,在用Iterator遍歷LinkedHashMap時,先得到的記錄肯定是先插入的。

TreeMap

存入元素的時候,自動對元素根據鍵進行升序排序

非執行緒安全

總結

正常情況下,使用HashMap,有其他需求,再使用LinkedHashMap和TreeMap

集合 Key Value 執行緒安全
TreeMap 不允許為null 允許為null 非執行緒安全
HashMap 允許為null 允許為null 非執行緒安全
LindedHashMap 允許為null 允許為null 非執行緒安全
HashTable 不允許為null 不允許為null 執行緒安全(效率低)