標籤:
每個家族都有一個最基本且最常用的資料類型:比如List系列的ArrayList,Map系列的HashMap,並且,它們的本質都是數組儲存結構。相似的是,每個家族都有一個Linked開頭的類,如List家族的LinkedList和Map家族的LinkedHashMap,這兩個類的儲存的資料結構又都是雙向鏈表(其實是連續數組添加了兩個方向的指標,所以既能與數組相容,又能夠有雙向鏈表的性質)。而引入雙向鏈表功能的目的就是為了能夠有序遍曆。
今天,我們就來介紹LinkedHashMap。
擴充HashMap增加雙向鏈表的實現,號稱是最占記憶體的資料結構。支援iterator()時按Entry的插入順序來排序(但是更新不算, 如果設定accessOrder屬性為true,則所有讀寫訪問都算)。
實現上是在Entry上再增加屬性before/after指標,插入時把自己加到Header Entry的前面去。如果所有讀寫訪問都要排序,還要把前後Entry的before/after拼接起來以在鏈表中刪除掉自己。
(本文出自:http://my.oschina.net/happyBKs/blog/493260)
下面的例子,我沒對LinkedHashMap和HashMap分別做了兩組比較,資料兩組分別一一對應。
我們可以發現,LinkedHashMap返回的key-value的順序,與我們插入put的順序一致,插入的順序不同,返回的順序也不同。而HashMap無論我們按照什麼順序插入,返回的順序都是唯一的,且與插入順序無關,HashMap的返回key-value的順序只與hashCode有關。
@Testpublic void testLinkedHashMap(){System.out.println("LinkedHashMap: N-M-S");LinkedHashMap<String,Integer> lhm=new LinkedHashMap<String,Integer>();lhm.put("NOKIA", 4000);lhm.put("MOTO", 3000);lhm.put("SAMGSUNG", 3500);for(Entry e:lhm.entrySet()){System.out.println(e.getKey()+": "+e.getValue());}System.out.println("LinkedHashMap: S-N-M");LinkedHashMap<String,Integer> lhm2=new LinkedHashMap<String,Integer>();lhm2.put("SAMGSUNG", 3500);lhm2.put("NOKIA", 4000);lhm2.put("MOTO", 3000);for(Entry e:lhm2.entrySet()){System.out.println(e.getKey()+": "+e.getValue());}System.out.println("HashMap: N-M-S");HashMap<String,Integer> hm=new HashMap<String,Integer>();hm.put("NOKIA", 4000);hm.put("MOTO", 3000);hm.put("SAMGSUNG", 3500);for(Entry e:hm.entrySet()){System.out.println(e.getKey()+": "+e.getValue());}System.out.println("HashMap: S-N-M");HashMap<String,Integer> hm2=new HashMap<String,Integer>();hm2.put("SAMGSUNG", 3500);hm2.put("NOKIA", 4000);hm2.put("MOTO", 3000);for(Entry e:hm2.entrySet()){System.out.println(e.getKey()+": "+e.getValue());}/*LinkedHashMap: N-M-SNOKIA: 4000MOTO: 3000SAMGSUNG: 3500LinkedHashMap: S-N-MSAMGSUNG: 3500NOKIA: 4000MOTO: 3000HashMap: N-M-SMOTO: 3000NOKIA: 4000SAMGSUNG: 3500HashMap: S-N-MMOTO: 3000NOKIA: 4000SAMGSUNG: 3500*///HashMap插入的索引值對是無序的,位置只與key關聯;LinkedHashMap與插入順序相關//實際上LinkedHashMap是在Entry上再增加屬性before/after指標,//插入時把自己加到Header Entry的前面去。//如果所有讀寫訪問都要排序,還要把前後Entry的before/after拼接起來以在鏈表中刪除掉自己。}
Java集合四大家族的故事(四)——Map家族的LinkedHashMap