Java: HashMap、HashTable、LinkedHashMap和TreeMap用法和區別
Java為資料結構中的對映定義了一個介面java.util.Map,它有四個實現類,分別是HashMap、HashTable、LinkedHashMap和TreeMap。本節例項主要介紹這4中例項的用法和區別。
關鍵技術剖析:
Map用於儲存鍵值對,根據鍵得到值,因此不允許鍵重複,值可以重複。
l (1)HashMap是一個最常用的Map,它根據鍵的hashCode值儲存資料,根據鍵可以直接獲取它的值,具有很快的訪問速度。HashMap最多隻允許一條記錄的鍵為null,不允許多條記錄的值為null。HashMap不支援執行緒的同步,即任一時刻可以有多個執行緒同時寫HashMap,可能會導致資料的不一致。如果需要同步,可以用Collections.synchronizedMap(HashMap map)方法使HashMap具有同步的能力。
l (2)Hashtable與HashMap類似,不同的是:它不允許記錄的鍵或者值為空;它支援執行緒的同步,即任一時刻只有一個執行緒能寫Hashtable,然而,這也導致了Hashtable在寫入時會比較慢。
l (3)LinkedHashMap儲存了記錄的插入順序,在用Iteraor遍歷LinkedHashMap時,先得到的記錄肯定是先插入的。在遍歷的時候會比HashMap慢。有HashMap的全部特性。
l (4)TreeMap能夠把它儲存的記錄根據鍵排序,預設是按升序排序,也可以指定排序的比較器。當用Iteraor遍歷TreeMap時,得到的記錄是排過序的。TreeMap的鍵和值都不能為空。
TreeMap取出來的是排序後的鍵值對。但如果您要按自然順序或自定義順序遍歷鍵,那麼TreeMap會更好。
LinkedHashMap 是HashMap的一個子類,如果需要輸出的順序和輸入的相同
public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("1", "Level 1"); map.put("2", "Level 2"); map.put("3", "Level 3"); map.put("a", "Level a"); map.put("b", "Level b"); map.put("c", "Level c"); Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> e = it.next(); System.out.println("Key: " + e.getKey() + "; Value: " + e.getValue()); } System.out.println("======================================"); Map<String, String> map1 = new TreeMap<String, String>(); map1.put("1", "Level 1"); map1.put("2", "Level 2"); map1.put("3", "Level 3"); map1.put("a", "Level a"); map1.put("b", "Level b"); map1.put("c", "Level c"); Iterator<Map.Entry<String, String>> it1 = map1.entrySet().iterator(); while (it1.hasNext()) { Map.Entry<String, String> e1 = it1.next(); System.out.println("Key: " + e1.getKey() + "; Value: " + e1.getValue()); } System.out.println("======================================"); Map<String, String> map2 = new LinkedHashMap<>(); map2.put("1", "Level 1"); map2.put("2", "Level 2"); map2.put("3", "Level 3"); map2.put("a", "Level a"); map2.put("b", "Level b"); map2.put("c", "Level c"); Iterator<Map.Entry<String, String>> it2 = map1.entrySet().iterator(); while (it2.hasNext()) { Map.Entry<String, String> e2 = it2.next(); System.out.println("Key: " + e2.getKey() + "; Value: " + e2.getValue()); } } 執行結果: Key: 3; Value: Level 3 Key: 2; Value: Level 2 Key: 1; Value: Level 1 Key: b; Value: Level b Key: c; Value: Level c Key: a; Value: Level a ====================================== Key: 1; Value: Level 1 Key: 2; Value: Level 2 Key: 3; Value: Level 3 Key: a; Value: Level a Key: b; Value: Level b Key: c; Value: Level c ====================================== Key: 1; Value: Level 1 Key: 2; Value: Level 2 Key: 3; Value: Level 3 Key: a; Value: Level a Key: b; Value: Level b Key: c; Value: Level c