LinkedHashMap是HashMap的字類(lèi),但它是有序的,那它是怎么實(shí)現(xiàn)的呢,看源碼
@Override
void addNewEntry(K key, V value, int hash, int index) {
LinkedEntry<K, V> header = this.header;
// Remove eldest entry if instructed to do so.
LinkedEntry<K, V> eldest = header.nxt;
if (eldest != header && removeEldestEntry(eldest)) {
remove(eldest.key);
}
// Create new entry, link it on to list, and put it into table
LinkedEntry<K, V> oldTail = header.prv;
LinkedEntry<K, V> newTail = new LinkedEntry<K,V>(
key, value, hash, table[index], header, oldTail);
table[index] = oldTail.nxt = header.prv = newTail;
}
主要就是這個(gè)this.header的值,在每次put數(shù)據(jù)時(shí)都會(huì)更新結(jié)構(gòu),最終形成如下圖所示的結(jié)構(gòu)

linkedHashMap.jpg
當(dāng)遍歷數(shù)據(jù)時(shí),先看下源碼
private abstract class LinkedHashIterator<T> implements Iterator<T> {
LinkedEntry<K, V> next = header.nxt;
LinkedEntry<K, V> lastReturned = null;
int expectedModCount = modCount;
public final boolean hasNext() {
return next != header;
}
final LinkedEntry<K, V> nextEntry() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
LinkedEntry<K, V> e = next;
if (e == header)
throw new NoSuchElementException();
next = e.nxt;
return lastReturned = e;
}
public final void remove() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (lastReturned == null)
throw new IllegalStateException();
LinkedHashMap.this.remove(lastReturned.key);
lastReturned = null;
expectedModCount = modCount;
}
}
就是循環(huán)獲取this.header的nxt參數(shù)值,直至獲取的到next值與header值相等,則結(jié)束,就如上圖中的紅色箭頭方向一樣。