HashMap和LinkedHashMap的區別

HashMap,LinkedHashMap,TreeMap都屬於Map測試

Map 主要用於存儲鍵(key)值(value)對,根據鍵獲得值,所以鍵不容許鍵重複,但容許值重複。線程

HashMap 
是一個最經常使用的Map,它根據鍵的HashCode 值存儲數據,根據鍵能夠直接獲取它的值,具備很快的訪問速度。HashMap最多隻容許一條記錄的鍵爲Null;容許多條記錄的值爲 Null;HashMap不支持線程的同步,即任一時刻能夠有多個線程同時寫HashMap;可能會致使數據的不一致。若是須要同步,能夠用 Collections的synchronizedMap方法使HashMap具備同步的能力。排序

                                                                                    
LinkedHashMap
LinkedHashMap也是一個HashMap,可是內部維持了一個雙向鏈表,能夠保持順序同步

 

TreeMap 能夠用於排序hash

 

HashMap的例子
public static void main(String[] args) {  it

      Map<String, String> map = new HashMap<String, String>(); io

      map.put("a3", "aa");map

      map.put("a2", "bb"); 方法

      map.put("b1", "cc");鏈表

      for (Iterator iterator = map.values().iterator(); iterator.hasNext();)     {

            String name = (String) iterator.next(); 

            System.out.println(name);   

     }  

  }

 

輸出:bbccaa

LinkedHashMap例子:

   

public static void main(String[] args) {   

     Map<String, String> map = new LinkedHashMap<String, String>();

     map.put("a3", "aa");       

     map.put("a2", "bb"); 

     map.put("b1", "cc"); 

     for (Iterator iterator = map.values().iterator(); iterator.hasNext();) {           

             String name = (String) iterator.next(); 

             System.out.println(name);     

     }

}


輸出:
aa
bb
cc

 

總結概括爲:linkedMap在於存儲數據你想保持進入的順序與被取出的順序一致的話,優先考慮LinkedMap,hashMap鍵只能容許爲一條爲空,value能夠容許爲多條爲空,鍵惟一,但值能夠多個。

經本人測試linkedMap鍵和值都不能夠爲空

相關文章
相關標籤/搜索