Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs fromHashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return trueimmediately prior to the invocation.)
其header头定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/** * The head of the doubly linked list. */ privatetransient Entry<K,V> header;
/** * Called by superclass constructors and pseudoconstructors (clone, * readObject) before any entries are inserted into the map. Initializes * the chain. */ @Override voidinit() { header = newEntry<>(-1, null, null, null); header.before = header.after = header; }
/** * This override alters behavior of superclass put method. It causes newly * allocated entry to get inserted at the end of the linked list and * removes the eldest entry if appropriate. */ voidaddEntry(int hash, K key, V value, int bucketIndex) { super.addEntry(hash, key, value, bucketIndex);
// Remove eldest entry if instructed Entry<K,V> eldest = header.after; if (removeEldestEntry(eldest)) { // 始终返回false removeEntryForKey(eldest.key); } }
/** * This override differs from addEntry in that it doesn't resize the * table or remove the eldest entry. */ voidcreateEntry(int hash, K key, V value, int bucketIndex) { HashMap.Entry<K,V> old = table[bucketIndex]; Entry<K,V> e = newEntry<>(hash, key, value, old); table[bucketIndex] = e; e.addBefore(header); size++; }
Entry: /** * Inserts this entry before the specified existing entry in the list. */ privatevoidaddBefore(Entry<K,V> existingEntry) { after = existingEntry; before = existingEntry.before; before.after = this; after.before = this; }