LinkedHashMap.java revision 90932be12a5e012347549ad293d15015eb2410a9
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.  Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27package java.util;
28
29import java.io.*;
30import java.util.function.Consumer;
31import java.util.function.BiConsumer;
32
33/**
34 * <p>Hash table and linked list implementation of the <tt>Map</tt> interface,
35 * with predictable iteration order.  This implementation differs from
36 * <tt>HashMap</tt> in that it maintains a doubly-linked list running through
37 * all of its entries.  This linked list defines the iteration ordering,
38 * which is normally the order in which keys were inserted into the map
39 * (<i>insertion-order</i>).  Note that insertion order is not affected
40 * if a key is <i>re-inserted</i> into the map.  (A key <tt>k</tt> is
41 * reinserted into a map <tt>m</tt> if <tt>m.put(k, v)</tt> is invoked when
42 * <tt>m.containsKey(k)</tt> would return <tt>true</tt> immediately prior to
43 * the invocation.)
44 *
45 * <p>This implementation spares its clients from the unspecified, generally
46 * chaotic ordering provided by {@link HashMap} (and {@link Hashtable}),
47 * without incurring the increased cost associated with {@link TreeMap}.  It
48 * can be used to produce a copy of a map that has the same order as the
49 * original, regardless of the original map's implementation:
50 * <pre>
51 *     void foo(Map m) {
52 *         Map copy = new LinkedHashMap(m);
53 *         ...
54 *     }
55 * </pre>
56 * This technique is particularly useful if a module takes a map on input,
57 * copies it, and later returns results whose order is determined by that of
58 * the copy.  (Clients generally appreciate having things returned in the same
59 * order they were presented.)
60 *
61 * <p>A special {@link #LinkedHashMap(int,float,boolean) constructor} is
62 * provided to create a linked hash map whose order of iteration is the order
63 * in which its entries were last accessed, from least-recently accessed to
64 * most-recently (<i>access-order</i>).  This kind of map is well-suited to
65 * building LRU caches.  Invoking the {@code put}, {@code putIfAbsent},
66 * {@code get}, {@code getOrDefault}, {@code compute}, {@code computeIfAbsent},
67 * {@code computeIfPresent}, or {@code merge} methods results
68 * in an access to the corresponding entry (assuming it exists after the
69 * invocation completes). The {@code replace} methods only result in an access
70 * of the entry if the value is replaced.  The {@code putAll} method generates one
71 * entry access for each mapping in the specified map, in the order that
72 * key-value mappings are provided by the specified map's entry set iterator.
73 * <i>No other methods generate entry accesses.</i>  In particular, operations
74 * on collection-views do <i>not</i> affect the order of iteration of the
75 * backing map. *
76 * <p>The {@link #removeEldestEntry(Map.Entry)} method may be overridden to
77 * impose a policy for removing stale mappings automatically when new mappings
78 * are added to the map.
79 *
80 * <p>This class provides all of the optional <tt>Map</tt> operations, and
81 * permits null elements.  Like <tt>HashMap</tt>, it provides constant-time
82 * performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and
83 * <tt>remove</tt>), assuming the hash function disperses elements
84 * properly among the buckets.  Performance is likely to be just slightly
85 * below that of <tt>HashMap</tt>, due to the added expense of maintaining the
86 * linked list, with one exception: Iteration over the collection-views
87 * of a <tt>LinkedHashMap</tt> requires time proportional to the <i>size</i>
88 * of the map, regardless of its capacity.  Iteration over a <tt>HashMap</tt>
89 * is likely to be more expensive, requiring time proportional to its
90 * <i>capacity</i>.
91 *
92 * <p>A linked hash map has two parameters that affect its performance:
93 * <i>initial capacity</i> and <i>load factor</i>.  They are defined precisely
94 * as for <tt>HashMap</tt>.  Note, however, that the penalty for choosing an
95 * excessively high value for initial capacity is less severe for this class
96 * than for <tt>HashMap</tt>, as iteration times for this class are unaffected
97 * by capacity.
98 *
99 * <p><strong>Note that this implementation is not synchronized.</strong>
100 * If multiple threads access a linked hash map concurrently, and at least
101 * one of the threads modifies the map structurally, it <em>must</em> be
102 * synchronized externally.  This is typically accomplished by
103 * synchronizing on some object that naturally encapsulates the map.
104 *
105 * If no such object exists, the map should be "wrapped" using the
106 * {@link Collections#synchronizedMap Collections.synchronizedMap}
107 * method.  This is best done at creation time, to prevent accidental
108 * unsynchronized access to the map:<pre>
109 *   Map m = Collections.synchronizedMap(new LinkedHashMap(...));</pre>
110 *
111 * A structural modification is any operation that adds or deletes one or more
112 * mappings or, in the case of access-ordered linked hash maps, affects
113 * iteration order.  In insertion-ordered linked hash maps, merely changing
114 * the value associated with a key that is already contained in the map is not
115 * a structural modification.  <strong>In access-ordered linked hash maps,
116 * merely querying the map with <tt>get</tt> is a structural
117 * modification.</strong>)
118 *
119 * <p>The iterators returned by the <tt>iterator</tt> method of the collections
120 * returned by all of this class's collection view methods are
121 * <em>fail-fast</em>: if the map is structurally modified at any time after
122 * the iterator is created, in any way except through the iterator's own
123 * <tt>remove</tt> method, the iterator will throw a {@link
124 * ConcurrentModificationException}.  Thus, in the face of concurrent
125 * modification, the iterator fails quickly and cleanly, rather than risking
126 * arbitrary, non-deterministic behavior at an undetermined time in the future.
127 *
128 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
129 * as it is, generally speaking, impossible to make any hard guarantees in the
130 * presence of unsynchronized concurrent modification.  Fail-fast iterators
131 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
132 * Therefore, it would be wrong to write a program that depended on this
133 * exception for its correctness:   <i>the fail-fast behavior of iterators
134 * should be used only to detect bugs.</i>
135 *
136 * <p>The spliterators returned by the spliterator method of the collections
137 * returned by all of this class's collection view methods are
138 * <em><a href="Spliterator.html#binding">late-binding</a></em>,
139 * <em>fail-fast</em>, and additionally report {@link Spliterator#ORDERED}.
140 *
141 * <p>This class is a member of the
142 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
143 * Java Collections Framework</a>.
144 *
145 * @implNote
146 * The spliterators returned by the spliterator method of the collections
147 * returned by all of this class's collection view methods are created from
148 * the iterators of the corresponding collections.
149 *
150 * @param <K> the type of keys maintained by this map
151 * @param <V> the type of mapped values
152 *
153 * @author  Josh Bloch
154 * @see     Object#hashCode()
155 * @see     Collection
156 * @see     Map
157 * @see     HashMap
158 * @see     TreeMap
159 * @see     Hashtable
160 * @since   1.4
161 */
162
163public class LinkedHashMap<K,V>
164    extends HashMap<K,V>
165    implements Map<K,V>
166{
167
168    private static final long serialVersionUID = 3801124242820219131L;
169
170    /**
171     * The head of the doubly linked list.
172     */
173    private transient LinkedHashMapEntry<K,V> header;
174
175    /**
176     * The iteration ordering method for this linked hash map: <tt>true</tt>
177     * for access-order, <tt>false</tt> for insertion-order.
178     *
179     * @serial
180     */
181    private final boolean accessOrder;
182
183    /**
184     * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
185     * with the specified initial capacity and load factor.
186     *
187     * @param  initialCapacity the initial capacity
188     * @param  loadFactor      the load factor
189     * @throws IllegalArgumentException if the initial capacity is negative
190     *         or the load factor is nonpositive
191     */
192    public LinkedHashMap(int initialCapacity, float loadFactor) {
193        super(initialCapacity, loadFactor);
194        accessOrder = false;
195    }
196
197    /**
198     * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
199     * with the specified initial capacity and a default load factor (0.75).
200     *
201     * @param  initialCapacity the initial capacity
202     * @throws IllegalArgumentException if the initial capacity is negative
203     */
204    public LinkedHashMap(int initialCapacity) {
205        super(initialCapacity);
206        accessOrder = false;
207    }
208
209    /**
210     * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
211     * with the default initial capacity (16) and load factor (0.75).
212     */
213    public LinkedHashMap() {
214        super();
215        accessOrder = false;
216    }
217
218    /**
219     * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with
220     * the same mappings as the specified map.  The <tt>LinkedHashMap</tt>
221     * instance is created with a default load factor (0.75) and an initial
222     * capacity sufficient to hold the mappings in the specified map.
223     *
224     * @param  m the map whose mappings are to be placed in this map
225     * @throws NullPointerException if the specified map is null
226     */
227    public LinkedHashMap(Map<? extends K, ? extends V> m) {
228        super(m);
229        accessOrder = false;
230    }
231
232    /**
233     * Constructs an empty <tt>LinkedHashMap</tt> instance with the
234     * specified initial capacity, load factor and ordering mode.
235     *
236     * @param  initialCapacity the initial capacity
237     * @param  loadFactor      the load factor
238     * @param  accessOrder     the ordering mode - <tt>true</tt> for
239     *         access-order, <tt>false</tt> for insertion-order
240     * @throws IllegalArgumentException if the initial capacity is negative
241     *         or the load factor is nonpositive
242     */
243    public LinkedHashMap(int initialCapacity,
244                         float loadFactor,
245                         boolean accessOrder) {
246        super(initialCapacity, loadFactor);
247        this.accessOrder = accessOrder;
248    }
249
250    /**
251     * Called by superclass constructors and pseudoconstructors (clone,
252     * readObject) before any entries are inserted into the map.  Initializes
253     * the chain.
254     */
255    @Override
256    void init() {
257        header = new LinkedHashMapEntry<>(-1, null, null, null);
258        header.before = header.after = header;
259    }
260
261    /**
262     * Transfers all entries to new table array.  This method is called
263     * by superclass resize.  It is overridden for performance, as it is
264     * faster to iterate using our linked list.
265     */
266    @Override
267    void transfer(HashMapEntry[] newTable, boolean rehash) {
268        int newCapacity = newTable.length;
269        for (LinkedHashMapEntry<K,V> e = header.after; e != header; e = e.after) {
270            if (rehash)
271                e.hash = (e.key == null) ? 0 : hash(e.key);
272            int index = indexFor(e.hash, newCapacity);
273            e.next = newTable[index];
274            newTable[index] = e;
275        }
276    }
277
278
279    /**
280     * Returns <tt>true</tt> if this map maps one or more keys to the
281     * specified value.
282     *
283     * @param value value whose presence in this map is to be tested
284     * @return <tt>true</tt> if this map maps one or more keys to the
285     *         specified value
286     */
287    public boolean containsValue(Object value) {
288        // Overridden to take advantage of faster iterator
289        if (value==null) {
290            for (LinkedHashMapEntry e = header.after; e != header; e = e.after)
291                if (e.value==null)
292                    return true;
293        } else {
294            for (LinkedHashMapEntry e = header.after; e != header; e = e.after)
295                if (value.equals(e.value))
296                    return true;
297        }
298        return false;
299    }
300
301    /**
302     * Returns the value to which the specified key is mapped,
303     * or {@code null} if this map contains no mapping for the key.
304     *
305     * <p>More formally, if this map contains a mapping from a key
306     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
307     * key.equals(k))}, then this method returns {@code v}; otherwise
308     * it returns {@code null}.  (There can be at most one such mapping.)
309     *
310     * <p>A return value of {@code null} does not <i>necessarily</i>
311     * indicate that the map contains no mapping for the key; it's also
312     * possible that the map explicitly maps the key to {@code null}.
313     * The {@link #containsKey containsKey} operation may be used to
314     * distinguish these two cases.
315     */
316    public V get(Object key) {
317        LinkedHashMapEntry<K,V> e = (LinkedHashMapEntry<K,V>)getEntry(key);
318        if (e == null)
319            return null;
320        e.recordAccess(this);
321        return e.value;
322    }
323
324    /**
325     * Removes all of the mappings from this map.
326     * The map will be empty after this call returns.
327     */
328    public void clear() {
329        super.clear();
330        header.before = header.after = header;
331    }
332
333    /**
334     * LinkedHashMap entry.
335     */
336    private static class LinkedHashMapEntry<K,V> extends HashMapEntry<K,V> {
337        // These fields comprise the doubly linked list used for iteration.
338        LinkedHashMapEntry<K,V> before, after;
339
340        LinkedHashMapEntry(int hash, K key, V value, HashMapEntry<K,V> next) {
341            super(hash, key, value, next);
342        }
343
344        /**
345         * Removes this entry from the linked list.
346         */
347        private void remove() {
348            before.after = after;
349            after.before = before;
350        }
351
352        /**
353         * Inserts this entry before the specified existing entry in the list.
354         */
355        private void addBefore(LinkedHashMapEntry<K,V> existingEntry) {
356            after  = existingEntry;
357            before = existingEntry.before;
358            before.after = this;
359            after.before = this;
360        }
361
362        /**
363         * This method is invoked by the superclass whenever the value
364         * of a pre-existing entry is read by Map.get or modified by Map.set.
365         * If the enclosing Map is access-ordered, it moves the entry
366         * to the end of the list; otherwise, it does nothing.
367         */
368        void recordAccess(HashMap<K,V> m) {
369            LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
370            if (lm.accessOrder) {
371                lm.modCount++;
372                remove();
373                addBefore(lm.header);
374            }
375        }
376
377        void recordRemoval(HashMap<K,V> m) {
378            remove();
379        }
380    }
381
382    private abstract class LinkedHashIterator<T> implements Iterator<T> {
383        LinkedHashMapEntry<K,V> nextEntry    = header.after;
384        LinkedHashMapEntry<K,V> lastReturned = null;
385
386        /**
387         * The modCount value that the iterator believes that the backing
388         * List should have.  If this expectation is violated, the iterator
389         * has detected concurrent modification.
390         */
391        int expectedModCount = modCount;
392
393        public boolean hasNext() {
394            return nextEntry != header;
395        }
396
397        public void remove() {
398            if (lastReturned == null)
399                throw new IllegalStateException();
400            if (modCount != expectedModCount)
401                throw new ConcurrentModificationException();
402
403            LinkedHashMap.this.remove(lastReturned.key);
404            lastReturned = null;
405            expectedModCount = modCount;
406        }
407
408        Entry<K,V> nextEntry() {
409            if (modCount != expectedModCount)
410                throw new ConcurrentModificationException();
411            if (nextEntry == header)
412                throw new NoSuchElementException();
413
414            LinkedHashMapEntry<K,V> e = lastReturned = nextEntry;
415            nextEntry = e.after;
416            return e;
417        }
418    }
419
420    private class KeyIterator extends LinkedHashIterator<K> {
421        public K next() { return nextEntry().getKey(); }
422    }
423
424    private class ValueIterator extends LinkedHashIterator<V> {
425        public V next() { return nextEntry().getValue(); }
426    }
427
428    private class EntryIterator extends LinkedHashIterator<Map.Entry<K,V>> {
429        public Map.Entry<K,V> next() { return nextEntry(); }
430    }
431
432    // These Overrides alter the behavior of superclass view iterator() methods
433    Iterator<K> newKeyIterator()   { return new KeyIterator();   }
434    Iterator<V> newValueIterator() { return new ValueIterator(); }
435    Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); }
436
437    /**
438     * This override alters behavior of superclass put method. It causes newly
439     * allocated entry to get inserted at the end of the linked list and
440     * removes the eldest entry if appropriate.
441     */
442    void addEntry(int hash, K key, V value, int bucketIndex) {
443        super.addEntry(hash, key, value, bucketIndex);
444
445        // Remove eldest entry if instructed
446        LinkedHashMapEntry<K,V> eldest = header.after;
447        if (removeEldestEntry(eldest)) {
448            removeEntryForKey(eldest.key);
449        }
450    }
451
452    /**
453     * Returns the eldest entry in the map, or {@code null} if the map is empty.
454     *
455     * Android-added.
456     *
457     * @hide
458     */
459    public Map.Entry<K, V> eldest() {
460        Entry<K, V> eldest = header.after;
461        return eldest != header ? eldest : null;
462    }
463
464    /**
465     * This override differs from addEntry in that it doesn't resize the
466     * table or remove the eldest entry.
467     */
468    void createEntry(int hash, K key, V value, int bucketIndex) {
469        HashMapEntry<K,V> old = table[bucketIndex];
470        LinkedHashMapEntry<K,V> e = new LinkedHashMapEntry<>(hash, key, value, old);
471        table[bucketIndex] = e;
472        e.addBefore(header);
473        size++;
474    }
475
476    /**
477     * Returns <tt>true</tt> if this map should remove its eldest entry.
478     * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
479     * inserting a new entry into the map.  It provides the implementor
480     * with the opportunity to remove the eldest entry each time a new one
481     * is added.  This is useful if the map represents a cache: it allows
482     * the map to reduce memory consumption by deleting stale entries.
483     *
484     * <p>Sample use: this override will allow the map to grow up to 100
485     * entries and then delete the eldest entry each time a new entry is
486     * added, maintaining a steady state of 100 entries.
487     * <pre>
488     *     private static final int MAX_ENTRIES = 100;
489     *
490     *     protected boolean removeEldestEntry(Map.Entry eldest) {
491     *        return size() > MAX_ENTRIES;
492     *     }
493     * </pre>
494     *
495     * <p>This method typically does not modify the map in any way,
496     * instead allowing the map to modify itself as directed by its
497     * return value.  It <i>is</i> permitted for this method to modify
498     * the map directly, but if it does so, it <i>must</i> return
499     * <tt>false</tt> (indicating that the map should not attempt any
500     * further modification).  The effects of returning <tt>true</tt>
501     * after modifying the map from within this method are unspecified.
502     *
503     * <p>This implementation merely returns <tt>false</tt> (so that this
504     * map acts like a normal map - the eldest element is never removed).
505     *
506     * @param    eldest The least recently inserted entry in the map, or if
507     *           this is an access-ordered map, the least recently accessed
508     *           entry.  This is the entry that will be removed it this
509     *           method returns <tt>true</tt>.  If the map was empty prior
510     *           to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
511     *           in this invocation, this will be the entry that was just
512     *           inserted; in other words, if the map contains a single
513     *           entry, the eldest entry is also the newest.
514     * @return   <tt>true</tt> if the eldest entry should be removed
515     *           from the map; <tt>false</tt> if it should be retained.
516     */
517    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
518        return false;
519    }
520
521    // Map overrides
522    public void forEach(BiConsumer<? super K, ? super V> action) {
523        if (action == null)
524            throw new NullPointerException();
525        int mc = modCount;
526        // Android modified - breaks from the loop when modCount != mc
527        for (LinkedHashMapEntry<K,V> e = header.after; modCount == mc && e != header; e = e.after)
528            action.accept(e.key, e.value);
529        if (modCount != mc)
530            throw new ConcurrentModificationException();
531    }
532}
533