大多數情況下,只要不涉及線程安全問題,Map基本都可以使用HashMap,不過HashMap有一個問題,就是迭代HashMap的順序并不是HashMap放置的順序,也就是無序。HashMap的這一缺點往往會帶來困擾,因為有些場景,我們期待一個有序的Map。
這個時候,LinkedHashMap就閃亮登場了,它雖然增加了時間和空間上的開銷,但是通過維護一個運行于所有條目的雙向鏈表,LinkedHashMap保證了元素迭代的順序。
四個關注點在LinkedHashMap上的答案
關 注 點 | 結 論 |
LinkedHashMap是否允許空 | Key和Value都允許空 |
LinkedHashMap是否允許重復數據 | Key重復會覆蓋、Value允許重復 |
LinkedHashMap是否有序 | 有序 |
LinkedHashMap是否線程安全 | 非線程安全 |
LinkedHashMap基本結構
關于LinkedHashMap,先提兩點:
1、LinkedHashMap可以認為是HashMap+LinkedList,即它既使用HashMap操作數據結構,又使用LinkedList維護插入元素的先后順序
2、LinkedHashMap的基本實現思想就是----多態。可以說,理解多態,再去理解LinkedHashMap原理會事半功倍;反之也是,對于LinkedHashMap原理的學習,也可以促進和加深對于多態的理解。
為什么可以這么說,首先看一下,LinkedHashMap的定義:
1
2
3
4
5
6
|
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> { ... } |
看到,LinkedHashMap是HashMap的子類,自然LinkedHashMap也就繼承了HashMap中所有非private的方法。再看一下LinkedHashMap中本身的方法:
看到LinkedHashMap中并沒有什么操作數據結構的方法,也就是說LinkedHashMap操作數據結構(比如put一個數據),和HashMap操作數據的方法完全一樣,無非就是細節上有一些的不同罷了。
LinkedHashMap和HashMap的區別在于它們的基本數據結構上,看一下LinkedHashMap的基本數據結構,也就是Entry:
1
2
3
4
5
6
7
8
|
private static class Entry<K,V> extends HashMap.Entry<K,V> { // These fields comprise the doubly linked list used for iteration. Entry<K,V> before, after; Entry( int hash, K key, V value, HashMap.Entry<K,V> next) { super (hash, key, value, next); } ... } |
列一下Entry里面有的一些屬性吧:
- K key
- V value
- Entry<K, V> next
- int hash
- Entry<K, V> before
- Entry<K, V> after
其中前面四個,也就是紅色部分是從HashMap.Entry中繼承過來的;后面兩個,也就是藍色部分是LinkedHashMap獨有的。不要搞錯了next和before、After,next是用于維護HashMap指定table位置上連接的Entry的順序的,before、After是用于維護Entry插入的先后順序的。
還是用圖表示一下,列一下屬性而已:
初始化LinkedHashMap
假如有這么一段代碼:
1
2
3
4
5
6
7
|
public static void main(String[] args) { LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>(); linkedHashMap.put( "111" , "111" ); linkedHashMap.put( "222" , "222" ); } |
首先是第3行~第4行,new一個LinkedHashMap出來,看一下做了什么:
1
2
3
4
|
public LinkedHashMap() { super (); accessOrder = false ; } |
1
2
3
4
5
6
|
public HashMap() { this .loadFactor = DEFAULT_LOAD_FACTOR; threshold = ( int )(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); table = new Entry[DEFAULT_INITIAL_CAPACITY]; init(); } |
1
2
3
4
|
void init() { header = new Entry<K,V>(- 1 , null , null , null ); header.before = header.after = header; } |
1
2
3
4
|
/** * The head of the doubly linked list. */ private transient Entry<K,V> header; |
這里出現了第一個多態:init()方法。盡管init()方法定義在HashMap中,但是由于:
1、LinkedHashMap重寫了init方法
2、實例化出來的是LinkedHashMap
因此實際調用的init方法是LinkedHashMap重寫的init方法。假設header的地址是0x00000000,那么初始化完畢,實際上是這樣的:
LinkedHashMap添加元素
繼續看LinkedHashMap添加元素,也就是put("111","111")做了什么,首先當然是調用HashMap的put方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public V put(K key, V value) { if (key == null ) return putForNullKey(value); int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null ; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess( this ); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null ; } |
第17行又是一個多態,因為LinkedHashMap重寫了addEntry方法,因此addEntry調用的是LinkedHashMap重寫了的方法:
1
2
3
4
5
6
7
8
9
10
11
12
|
void addEntry( int hash, K key, V value, int bucketIndex) { createEntry(hash, key, value, bucketIndex); // Remove eldest entry if instructed, else grow capacity if appropriate Entry<K,V> eldest = header.after; if (removeEldestEntry(eldest)) { removeEntryForKey(eldest.key); } else { if (size >= threshold) resize( 2 * table.length); } } |
因為LinkedHashMap由于其本身維護了插入的先后順序,因此LinkedHashMap可以用來做緩存,第5行~第7行是用來支持FIFO算法的,這里暫時不用去關心它。看一下createEntry方法:
1
2
3
4
5
6
7
|
void createEntry( int hash, K key, V value, int bucketIndex) { HashMap.Entry<K,V> old = table[bucketIndex]; Entry<K,V> e = new Entry<K,V>(hash, key, value, old); table[bucketIndex] = e; e.addBefore(header); size++; } |
1
2
3
4
5
6
|
private void addBefore(Entry<K,V> existingEntry) { after = existingEntry; before = existingEntry.before; before.after = this ; after.before = this ; } |
第2行~第4行的代碼和HashMap沒有什么不同,新添加的元素放在table[i]上,差別在于LinkedHashMap還做了addBefore操作,這四行代碼的意思就是讓新的Entry和原鏈表生成一個雙向鏈表。假設字符串111放在位置table[1]上,生成的Entry地址為0x00000001,那么用圖表示是這樣的:
如果熟悉LinkedList的源碼應該不難理解,還是解釋一下,注意下existingEntry表示的是header:
1、after=existingEntry,即新增的Entry的after=header地址,即after=0x00000000
2、before=existingEntry.before,即新增的Entry的before是header的before的地址,header的before此時是0x00000000,因此新增的Entry的before=0x00000000
3、before.after=this,新增的Entry的before此時為0x00000000即header,header的after=this,即header的after=0x00000001
4、after.before=this,新增的Entry的after此時為0x00000000即header,header的before=this,即header的before=0x00000001
這樣,header與新增的Entry的一個雙向鏈表就形成了。再看,新增了字符串222之后是什么樣的,假設新增的Entry的地址為0x00000002,生成到table[2]上,用圖表示是這樣的:
就不細解釋了,只要before、after清除地知道代表的是哪個Entry的就不會有什么問題。
總得來看,再說明一遍,LinkedHashMap的實現就是HashMap+LinkedList的實現方式,以HashMap維護數據結構,以LinkList的方式維護數據插入順序。
利用LinkedHashMap實現LRU算法緩存
前面講了LinkedHashMap添加元素,刪除、修改元素就不說了,比較簡單,和HashMap+LinkedList的刪除、修改元素大同小異,下面講一個新的內容。
LinkedHashMap可以用來作緩存,比方說LRUCache,看一下這個類的代碼,很簡單,就十幾行而已:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class LRUCache extends LinkedHashMap { public LRUCache( int maxSize) { super (maxSize, 0 .75F, true ); maxElements = maxSize; } protected boolean removeEldestEntry(java.util.Map.Entry eldest) { return size() > maxElements; } private static final long serialVersionUID = 1L; protected int maxElements; } |
顧名思義,LRUCache就是基于LRU算法的Cache(緩存),這個類繼承自LinkedHashMap,而類中看到沒有什么特別的方法,這說明LRUCache實現緩存LRU功能都是源自LinkedHashMap的。LinkedHashMap可以實現LRU算法的緩存基于兩點:
1、LinkedList首先它是一個Map,Map是基于K-V的,和緩存一致
2、LinkedList提供了一個boolean值可以讓用戶指定是否實現LRU
那么,首先我們了解一下什么是LRU:LRU即Least Recently Used,最近最少使用,也就是說,當緩存滿了,會優先淘汰那些最近最不常訪問的數據。比方說數據a,1天前訪問了;數據b,2天前訪問了,緩存滿了,優先會淘汰數據b。
我們看一下LinkedList帶boolean型參數的構造方法:
1
2
3
4
5
6
|
public LinkedHashMap( int initialCapacity, float loadFactor, boolean accessOrder) { super (initialCapacity, loadFactor); this .accessOrder = accessOrder; } |
就是這個accessOrder,它表示:
(1)false,所有的Entry按照插入的順序排列
(2)true,所有的Entry按照訪問的順序排列
第二點的意思就是,如果有1 2 3這3個Entry,那么訪問了1,就把1移到尾部去,即2 3 1。每次訪問都把訪問的那個數據移到雙向隊列的尾部去,那么每次要淘汰數據的時候,雙向隊列最頭的那個數據不就是最不常訪問的那個數據了嗎?換句話說,雙向鏈表最頭的那個數據就是要淘汰的數據。
"訪問",這個詞有兩層意思:
1、根據Key拿到Value,也就是get方法
2、修改Key對應的Value,也就是put方法
首先看一下get方法,它在LinkedHashMap中被重寫:
1
2
3
4
5
6
7
|
public V get(Object key) { Entry<K,V> e = (Entry<K,V>)getEntry(key); if (e == null ) return null ; e.recordAccess( this ); return e.value; } |
然后是put方法,沿用父類HashMap的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public V put(K key, V value) { if (key == null ) return putForNullKey(value); int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null ; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess( this ); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null ; } |
修改數據也就是第6行~第14行的代碼。看到兩端代碼都有一個共同點:都調用了recordAccess方法,且這個方法是Entry中的方法,也就是說每次的recordAccess操作的都是某一個固定的Entry。
recordAccess,顧名思義,記錄訪問,也就是說你這次訪問了雙向鏈表,我就把你記錄下來,怎么記錄?把你訪問的Entry移到尾部去。這個方法在HashMap中是一個空方法,就是用來給子類記錄訪問用的,看一下LinkedHashMap中的實現:
1
2
3
4
5
6
7
8
|
void recordAccess(HashMap<K,V> m) { LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m; if (lm.accessOrder) { lm.modCount++; remove(); addBefore(lm.header); } } |
1
2
3
4
|
private void remove() { before.after = after; after.before = before; } |
1
2
3
4
5
6
|
private void addBefore(Entry<K,V> existingEntry) { after = existingEntry; before = existingEntry.before; before.after = this ; after.before = this ; } |
看到每次recordAccess的時候做了兩件事情:
1、把待移動的Entry的前后Entry相連
2、把待移動的Entry移動到尾部
當然,這一切都是基于accessOrder=true的情況下。最后用一張圖表示一下整個recordAccess的過程吧:
代碼演示LinkedHashMap按照訪問順序排序的效果
最后代碼演示一下LinkedList按照訪問順序排序的效果,驗證一下上一部分LinkedHashMap的LRU功能:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
public static void main(String[] args) { LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>( 16 , 0 .75f, true ); linkedHashMap.put( "111" , "111" ); linkedHashMap.put( "222" , "222" ); linkedHashMap.put( "333" , "333" ); linkedHashMap.put( "444" , "444" ); loopLinkedHashMap(linkedHashMap); linkedHashMap.get( "111" ); loopLinkedHashMap(linkedHashMap); linkedHashMap.put( "222" , "2222" ); loopLinkedHashMap(linkedHashMap); } public static void loopLinkedHashMap(LinkedHashMap<String, String> linkedHashMap) { Set<Map.Entry<String, String>> set = inkedHashMap.entrySet(); Iterator<Map.Entry<String, String>> iterator = set.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + "\t" ); } System.out.println(); } |
注意這里的構造方法要用三個參數那個且最后的要傳入true,這樣才表示按照訪問順序排序。看一下代碼運行結果:
1
2
3
|
111=111 222=222 333=333 444=444 222=222 333=333 444=444 111=111 333=333 444=444 111=111 222=2222 |
代碼運行結果證明了兩點:
1、LinkedList是有序的
2、每次訪問一個元素(get或put),被訪問的元素都被提到最后面去了
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持服務器之家!
原文鏈接:http://www.cnblogs.com/xrq730/p/5052323.html