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