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