LinkedHashMap.java 16.1 KB
Newer Older
Bryce McKinlay committed
1 2
/* LinkedHashMap.java -- a class providing hashtable data structure,
   mapping Object --> Object, with linked list traversal
3
   Copyright (C) 2001, 2002 Free Software Foundation, Inc.
Bryce McKinlay committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */
Bryce McKinlay committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52


package java.util;

/**
 * This class provides a hashtable-backed implementation of the
 * Map interface, with predictable traversal order.
 * <p>
 *
 * It uses a hash-bucket approach; that is, hash collisions are handled
 * by linking the new node off of the pre-existing node (or list of
 * nodes).  In this manner, techniques such as linear probing (which
 * can cause primary clustering) and rehashing (which does not fit very
 * well with Java's method of precomputing hash codes) are avoided.  In
 * addition, this maintains a doubly-linked list which tracks either
53 54 55 56 57 58 59 60 61 62 63
 * insertion or access order.
 * <p>
 *
 * In insertion order, calling <code>put</code> adds the key to the end of
 * traversal, unless the key was already in the map; changing traversal order
 * requires removing and reinserting a key.  On the other hand, in access
 * order, all calls to <code>put</code> and <code>get</code> cause the
 * accessed key to move to the end of the traversal list.  Note that any
 * accesses to the map's contents via its collection views and iterators do
 * not affect the map's traversal order, since the collection views do not
 * call <code>put</code> or <code>get</code>.
Bryce McKinlay committed
64 65 66 67 68 69 70 71 72
 * <p>
 *
 * One of the nice features of tracking insertion order is that you can
 * copy a hashtable, and regardless of the implementation of the original,
 * produce the same results when iterating over the copy.  This is possible
 * without needing the overhead of <code>TreeMap</code>.
 * <p>
 *
 * When using this {@link #LinkedHashMap(int, float, boolean) constructor},
73 74 75 76
 * you can build an access-order mapping.  This can be used to implement LRU
 * caches, for example.  By overriding {@link #removeEldestEntry(Map.Entry)},
 * you can also control the removal of the oldest entry, and thereby do
 * things like keep the map at a fixed size.
Bryce McKinlay committed
77 78 79
 * <p>
 *
 * Under ideal circumstances (no collisions), LinkedHashMap offers O(1) 
80
 * performance on most operations (<code>containsValue()</code> is,
Bryce McKinlay committed
81
 * of course, O(n)).  In the worst case (all keys map to the same 
82 83 84 85
 * hash code -- very unlikely), most operations are O(n).  Traversal is
 * faster than in HashMap (proportional to the map size, and not the space
 * allocated for the map), but other operations may be slower because of the
 * overhead of the maintaining the traversal order list.
Bryce McKinlay committed
86 87 88 89 90 91 92 93 94 95 96 97 98
 * <p>
 *
 * LinkedHashMap accepts the null key and null values.  It is not
 * synchronized, so if you need multi-threaded access, consider using:<br>
 * <code>Map m = Collections.synchronizedMap(new LinkedHashMap(...));</code>
 * <p>
 *
 * The iterators are <i>fail-fast</i>, meaning that any structural
 * modification, except for <code>remove()</code> called on the iterator
 * itself, cause the iterator to throw a
 * {@link ConcurrentModificationException} rather than exhibit
 * non-deterministic behavior.
 *
99
 * @author Eric Blake (ebb9@email.byu.edu)
Bryce McKinlay committed
100 101 102 103 104 105 106
 * @see Object#hashCode()
 * @see Collection
 * @see Map
 * @see HashMap
 * @see TreeMap
 * @see Hashtable
 * @since 1.4
107
 * @status updated to 1.4
Bryce McKinlay committed
108 109 110 111 112 113 114 115 116
 */
public class LinkedHashMap extends HashMap
{
  /**
   * Compatible with JDK 1.4.
   */
  private static final long serialVersionUID = 3801124242820219131L;

  /**
117
   * The oldest Entry to begin iteration at.
Bryce McKinlay committed
118
   */
119
  transient LinkedHashEntry root;
Bryce McKinlay committed
120 121 122 123

  /**
   * The iteration order of this linked hash map: <code>true</code> for
   * access-order, <code>false</code> for insertion-order.
124 125
   *
   * @serial true for access order traversal
Bryce McKinlay committed
126 127 128 129 130 131 132 133 134
   */
  final boolean accessOrder;

  /**
   * Class to represent an entry in the hash table. Holds a single key-value
   * pair and the doubly-linked insertion order list.
   */
  class LinkedHashEntry extends HashEntry
  {
135 136 137 138
    /**
     * The predecessor in the iteration list. If this entry is the root
     * (eldest), pred points to the newest entry.
     */
Bryce McKinlay committed
139
    LinkedHashEntry pred;
140

Bryce McKinlay committed
141 142 143 144 145
    /** The successor in the iteration list, null if this is the newest. */
    LinkedHashEntry succ;

    /**
     * Simple constructor.
146
     *
Bryce McKinlay committed
147 148 149 150 151 152
     * @param key the key
     * @param value the value
     */
    LinkedHashEntry(Object key, Object value)
    {
      super(key, value);
153 154 155 156 157 158 159 160 161 162 163
      if (root == null)
        {
          root = this;
          pred = this;
        }
      else
        {
          pred = root.pred;
          pred.succ = this;
          root.pred = this;
        }
Bryce McKinlay committed
164 165 166
    }

    /**
167 168 169
     * Called when this entry is accessed via put or get. This version does
     * the necessary bookkeeping to keep the doubly-linked list in order,
     * after moving this element to the newest position in access order.
Bryce McKinlay committed
170
     */
171
    void access()
Bryce McKinlay committed
172 173 174
    {
      if (accessOrder && succ != null)
        {
175 176 177 178 179 180 181
          modCount++;
          if (this == root)
            {
              root = succ;
              pred.succ = this;
              succ = null;
            }
Bryce McKinlay committed
182
          else
183 184 185 186 187 188 189
            {
              pred.succ = succ;
              succ.pred = pred;
              succ = null;
              pred = root.pred;
              pred.succ = this;
            }
Bryce McKinlay committed
190 191 192 193 194 195
        }
    }

    /**
     * Called when this entry is removed from the map. This version does
     * the necessary bookkeeping to keep the doubly-linked list in order.
196
     *
Bryce McKinlay committed
197 198 199 200
     * @return the value of this key as it is removed
     */
    Object cleanup()
    {
201 202 203 204 205 206 207 208 209 210 211
      if (this == root)
        {
          root = succ;
          if (succ != null)
            succ.pred = pred;
        }
      else if (succ == null)
        {
          pred.succ = null;
          root.pred = pred;
        }
Bryce McKinlay committed
212
      else
213 214 215 216
        {
          pred.succ = succ;
          succ.pred = pred;
        }
Bryce McKinlay committed
217 218
      return value;
    }
219
  } // class LinkedHashEntry
Bryce McKinlay committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

  /**
   * Construct a new insertion-ordered LinkedHashMap with the default
   * capacity (11) and the default load factor (0.75).
   */
  public LinkedHashMap()
  {
    super();
    accessOrder = false;
  }

  /**
   * Construct a new insertion-ordered LinkedHashMap from the given Map,
   * with initial capacity the greater of the size of <code>m</code> or
   * the default of 11.
   * <p>
   *
   * Every element in Map m will be put into this new HashMap, in the
   * order of m's iterator.
   *
   * @param m a Map whose key / value pairs will be put into
   *          the new HashMap.  <b>NOTE: key / value pairs
   *          are not cloned in this constructor.</b>
   * @throws NullPointerException if m is null
   */
  public LinkedHashMap(Map m)
  {
    super(m);
    accessOrder = false;
  }

  /**
   * Construct a new insertion-ordered LinkedHashMap with a specific
   * inital capacity and default load factor of 0.75.
   *
255 256
   * @param initialCapacity the initial capacity of this HashMap (&gt;= 0)
   * @throws IllegalArgumentException if (initialCapacity &lt; 0)
Bryce McKinlay committed
257 258 259 260 261 262 263 264 265 266 267
   */
  public LinkedHashMap(int initialCapacity)
  {
    super(initialCapacity);
    accessOrder = false;
  }

  /**
   * Construct a new insertion-orderd LinkedHashMap with a specific
   * inital capacity and load factor.
   *
268 269 270 271
   * @param initialCapacity the initial capacity (&gt;= 0)
   * @param loadFactor the load factor (&gt; 0, not NaN)
   * @throws IllegalArgumentException if (initialCapacity &lt; 0) ||
   *                                     ! (loadFactor &gt; 0.0)
Bryce McKinlay committed
272 273 274 275 276 277 278 279 280 281 282
   */
  public LinkedHashMap(int initialCapacity, float loadFactor)
  {
    super(initialCapacity, loadFactor);
    accessOrder = false;
  }

  /**
   * Construct a new LinkedHashMap with a specific inital capacity, load
   * factor, and ordering mode.
   *
283 284
   * @param initialCapacity the initial capacity (&gt;=0)
   * @param loadFactor the load factor (&gt;0, not NaN)
Bryce McKinlay committed
285
   * @param accessOrder true for access-order, false for insertion-order
286 287
   * @throws IllegalArgumentException if (initialCapacity &lt; 0) ||
   *                                     ! (loadFactor &gt; 0.0)
Bryce McKinlay committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301
   */
  public LinkedHashMap(int initialCapacity, float loadFactor,
                       boolean accessOrder)
  {
    super(initialCapacity, loadFactor);
    this.accessOrder = accessOrder;
  }

  /**
   * Clears the Map so it has no keys. This is O(1).
   */
  public void clear()
  {
    super.clear();
302
    root = null;
Bryce McKinlay committed
303 304 305
  }

  /**
306 307
   * Returns <code>true</code> if this HashMap contains a value
   * <code>o</code>, such that <code>o.equals(value)</code>.
Bryce McKinlay committed
308 309
   *
   * @param value the value to search for in this HashMap
310
   * @return <code>true</code> if at least one key maps to the value
Bryce McKinlay committed
311 312 313
   */
  public boolean containsValue(Object value)
  {
314
    LinkedHashEntry e = root;
Bryce McKinlay committed
315 316
    while (e != null)
      {
317
        if (equals(value, e.value))
Bryce McKinlay committed
318 319 320 321 322 323 324 325
          return true;
        e = e.succ;
      }
    return false;
  }

  /**
   * Return the value in this Map associated with the supplied key,
326
   * or <code>null</code> if the key maps to nothing.  If this is an
Bryce McKinlay committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
   * access-ordered Map and the key is found, this performs structural
   * modification, moving the key to the newest end of the list. NOTE:
   * Since the value could also be null, you must use containsKey to
   * see if this key actually maps to something.
   *
   * @param key the key for which to fetch an associated value
   * @return what the key maps to, if present
   * @see #put(Object, Object)
   * @see #containsKey(Object)
   */
  public Object get(Object key)
  {
    int idx = hash(key);
    HashEntry e = buckets[idx];
    while (e != null)
      {
343
        if (equals(key, e.key))
Bryce McKinlay committed
344
          {
345
            e.access();
Bryce McKinlay committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
            return e.value;
          }
        e = e.next;
      }
    return null;
  }

  /**
   * Returns <code>true</code> if this map should remove the eldest entry.
   * This method is invoked by all calls to <code>put</code> and
   * <code>putAll</code> which place a new entry in the map, providing
   * the implementer an opportunity to remove the eldest entry any time
   * a new one is added.  This can be used to save memory usage of the
   * hashtable, as well as emulating a cache, by deleting stale entries.
   * <p>
   *
   * For example, to keep the Map limited to 100 entries, override as follows:
363 364 365 366 367 368 369
   * <pre>
   * private static final int MAX_ENTRIES = 100;
   * protected boolean removeEldestEntry(Map.Entry eldest)
   * {
   *   return size() &gt; MAX_ENTRIES;
   * }
   * </pre><p>
Bryce McKinlay committed
370 371 372 373
   *
   * Typically, this method does not modify the map, but just uses the
   * return value as an indication to <code>put</code> whether to proceed.
   * However, if you override it to modify the map, you must return false
374 375 376 377
   * (indicating that <code>put</code> should leave the modified map alone),
   * or you face unspecified behavior.  Remember that in access-order mode,
   * even calling <code>get</code> is a structural modification, but using
   * the collections views (such as <code>keySet</code>) is not.
Bryce McKinlay committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
   * <p>
   *
   * This method is called after the eldest entry has been inserted, so
   * if <code>put</code> was called on a previously empty map, the eldest
   * entry is the one you just put in! The default implementation just
   * returns <code>false</code>, so that this map always behaves like
   * a normal one with unbounded growth.
   *
   * @param eldest the eldest element which would be removed if this
   *        returns true. For an access-order map, this is the least
   *        recently accessed; for an insertion-order map, this is the
   *        earliest element inserted.
   * @return true if <code>eldest</code> should be removed
   */
  protected boolean removeEldestEntry(Map.Entry eldest)
  {
    return false;
  }

397 398
  /**
   * Helper method called by <code>put</code>, which creates and adds a
Bryce McKinlay committed
399 400 401 402 403
   * new Entry, followed by performing bookkeeping (like removeEldestEntry).
   *
   * @param key the key of the new Entry
   * @param value the value
   * @param idx the index in buckets where the new Entry belongs
404
   * @param callRemove whether to call the removeEldestEntry method
Bryce McKinlay committed
405 406
   * @see #put(Object, Object)
   * @see #removeEldestEntry(Map.Entry)
407
   * @see LinkedHashEntry#LinkedHashEntry(Object, Object)
Bryce McKinlay committed
408 409 410 411 412 413
   */
  void addEntry(Object key, Object value, int idx, boolean callRemove)
  {
    LinkedHashEntry e = new LinkedHashEntry(key, value);
    e.next = buckets[idx];
    buckets[idx] = e;
414 415
    if (callRemove && removeEldestEntry(root))
      remove(root);
Bryce McKinlay committed
416 417
  }

418 419
  /**
   * Helper method, called by clone() to reset the doubly-linked list.
420
   *
421 422 423
   * @param m the map to add entries from
   * @see #clone()
   */
Bryce McKinlay committed
424 425
  void putAllInternal(Map m)
  {
426
    root = null;
Bryce McKinlay committed
427 428 429 430 431 432
    super.putAllInternal(m);
  }

  /**
   * Generates a parameterized iterator. This allows traversal to follow
   * the doubly-linked list instead of the random bin order of HashMap.
433
   *
Bryce McKinlay committed
434 435 436 437 438 439 440
   * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
   * @return the appropriate iterator
   */
  Iterator iterator(final int type)
  {
    return new Iterator()
    {
441 442
      /** The current Entry. */
      LinkedHashEntry current = root;
Bryce McKinlay committed
443

444
      /** The previous Entry returned by next(). */
Bryce McKinlay committed
445 446
      LinkedHashEntry last;

447
      /** The number of known modifications to the backing Map. */
Bryce McKinlay committed
448 449 450 451
      int knownMod = modCount;

      /**
       * Returns true if the Iterator has more elements.
452
       *
Bryce McKinlay committed
453 454 455 456 457 458 459 460 461 462 463 464
       * @return true if there are more elements
       * @throws ConcurrentModificationException if the HashMap was modified
       */
      public boolean hasNext()
      {
        if (knownMod != modCount)
          throw new ConcurrentModificationException();
        return current != null;
      }

      /**
       * Returns the next element in the Iterator's sequential view.
465
       *
Bryce McKinlay committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
       * @return the next element
       * @throws ConcurrentModificationException if the HashMap was modified
       * @throws NoSuchElementException if there is none
       */
      public Object next()
      {
        if (knownMod != modCount)
          throw new ConcurrentModificationException();
        if (current == null)
          throw new NoSuchElementException();
        last = current;
        current = current.succ;
        return type == VALUES ? last.value : type == KEYS ? last.key : last;
      }
      
      /**
       * Removes from the backing HashMap the last element which was fetched
483 484
       * with the <code>next()</code> method.
       *
Bryce McKinlay committed
485 486 487 488 489 490 491 492 493 494 495
       * @throws ConcurrentModificationException if the HashMap was modified
       * @throws IllegalStateException if called when there is no last element
       */
      public void remove()
      {
        if (knownMod != modCount)
          throw new ConcurrentModificationException();
        if (last == null)
          throw new IllegalStateException();
        LinkedHashMap.this.remove(last.key);
        last = null;
496
        knownMod++;
Bryce McKinlay committed
497 498 499
      }
    };
  }
500
} // class LinkedHashMap