HashMap是一個比較基礎的Map的實現,HashMap的讀取是無序和隨機的。LinkedHashMap是繼承自HashMap,並提供了HashMap沒有的特性:保持數據的順序讀寫,便可以根據輸入的順序輸出。java
TreeMap也能夠保證順序讀寫,TreeMap的底層數據結構是紅黑樹,讀寫的算法複雜度爲O(logn),而LinkedHashMap的讀能夠達到O(1),在性能上面比TreeMap更好一些。算法
LinkedHashMap保存了記錄的插入順序,在用Iterator遍歷LinkedHashMap時,先獲得的記錄確定是先插入的.在遍歷的時候會比HashMap慢。數據結構
private transient Entry<K,V> header; //accessOrder 標記是否爲訪問順序,true是訪問順序,false爲插入順序,在初始化map的時候,默認爲false private final boolean accessOrder;
public LinkedHashMap() { super(); accessOrder = false; }
在HashMap父類中定義了init方法,但實現是空的,在LinkedHashMap中實現以下:header鏈表初始化。性能
void init() { this.header = new LinkedHashMap.Entry(-1, (Object)null, (Object)null, (java.util.HashMap.Entry)null); this.header.before = this.header.after = this.header; }
LinkedHashMap的put方法沒有重寫,採用的是父類的put方法,先看下HashMap.put()的源碼:this
public V put(K key, V value) { if (table == EMPTY_TABLE) { inflateTable(threshold); } if (key == null) return putForNullKey(value); int hash = hash(key); 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; }
void recordAccess(HashMap<K,V> m) { LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m; if (lm.accessOrder) { lm.modCount++; remove(); addBefore(lm.header); } }
void createEntry(int hash, K key, V value, int bucketIndex) { HashMap.Entry<K,V> old = table[bucketIndex]; Entry<K,V> e = new Entry<>(hash, key, value, old); table[bucketIndex] = e; e.addBefore(header); size++; }
/** * Inserts this entry before the specified existing entry in the list. */ private void addBefore(Entry<K,V> existingEntry) { after = existingEntry; before = existingEntry.before; before.after = this; after.before = this; }
再次看下get方法的源碼:排序
public V get(Object var1) { LinkedHashMap.Entry var2 = (LinkedHashMap.Entry)this.getEntry(var1); //getEntry方法是使用父類HashMap的方法。 if(var2 == null) { return null; } else { var2不爲空的時候,記錄下寫入順序。 var2.recordAccess(this); return var2.value; } }
final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } int hash = (key == null) ? 0 : hash(key); for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } return null; }