Java集合四大家族的故事(四)——Map家族的LinkedHashMap

來源:互聯網
上載者:User

標籤:

每個家族都有一個最基本且最常用的資料類型:比如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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.