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