001: /*
002: * @(#)LinkedHashMap.java 1.14 06/10/10
003: *
004: * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
005: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
006: *
007: * This program is free software; you can redistribute it and/or
008: * modify it under the terms of the GNU General Public License version
009: * 2 only, as published by the Free Software Foundation.
010: *
011: * This program is distributed in the hope that it will be useful, but
012: * WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014: * General Public License version 2 for more details (a copy is
015: * included at /legal/license.txt).
016: *
017: * You should have received a copy of the GNU General Public License
018: * version 2 along with this work; if not, write to the Free Software
019: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
020: * 02110-1301 USA
021: *
022: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
023: * Clara, CA 95054 or visit www.sun.com if you need additional
024: * information or have any questions.
025: */
026:
027: package java.util;
028:
029: import java.io.*;
030:
031: /**
032: * <p>Hash table and linked list implementation of the <tt>Map</tt> interface,
033: * with predictable iteration order. This implementation differs from
034: * <tt>HashMap</tt> in that it maintains a doubly-linked list running through
035: * all of its entries. This linked list defines the iteration ordering,
036: * which is normally the order in which keys were inserted into the map
037: * (<i>insertion-order</i>). Note that insertion order is not affected
038: * if a key is <i>re-inserted</i> into the map. (A key <tt>k</tt> is
039: * reinserted into a map <tt>m</tt> if <tt>m.put(k, v)</tt> is invoked when
040: * <tt>m.containsKey(k)</tt> would return <tt>true</tt> immediately prior to
041: * the invocation.)
042: *
043: * <p>This implementation spares its clients from the unspecified, generally
044: * chaotic ordering provided by {@link HashMap} (and {@link Hashtable}),
045: * without incurring the increased cost associated with {@link TreeMap}. It
046: * can be used to produce a copy of a map that has the same order as the
047: * original, regardless of the original map's implementation:
048: * <pre>
049: * void foo(Map m) {
050: * Map copy = new LinkedHashMap(m);
051: * ...
052: * }
053: * </pre>
054: * This technique is particularly useful if a module takes a map on input,
055: * copies it, and later returns results whose order is determined by that of
056: * the copy. (Clients generally appreciate having things returned in the same
057: * order they were presented.)
058: *
059: * <p>A special {@link #LinkedHashMap(int,float,boolean) constructor} is
060: * provided to create a linked hash map whose order of iteration is the order
061: * in which its entries were last accessed, from least-recently accessed to
062: * most-recently (<i>access-order</i>). This kind of map is well-suited to
063: * building LRU caches. Invoking the <tt>put</tt> or <tt>get</tt> method
064: * results in an access to the corresponding entry (assuming it exists after
065: * the invocation completes). The <tt>putAll</tt> method generates one entry
066: * access for each mapping in the specified map, in the order that key-value
067: * mappings are provided by the specified map's entry set iterator. <i>No
068: * other methods generate entry accesses.</i> In particular, operations on
069: * collection-views do <i>not</i> affect the order of iteration of the backing
070: * map.
071: *
072: * <p>The {@link #removeEldestEntry(Map.Entry)} method may be overridden to
073: * impose a policy for removing stale mappings automatically when new mappings
074: * are added to the map.
075: *
076: * <p>This class provides all of the optional <tt>Map</tt> operations, and
077: * permits null elements. Like <tt>HashMap</tt>, it provides constant-time
078: * performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and
079: * <tt>remove</tt>), assuming the the hash function disperses elements
080: * properly among the buckets. Performance is likely to be just slightly
081: * below that of <tt>HashMap</tt>, due to the added expense of maintaining the
082: * linked list, with one exception: Iteration over the collection-views
083: * of a <tt>LinkedHashMap</tt> requires time proportional to the <i>size</i>
084: * of the map, regardless of its capacity. Iteration over a <tt>HashMap</tt>
085: * is likely to be more expensive, requiring time proportional to its
086: * <i>capacity</i>.
087: *
088: * <p>A linked hash map has two parameters that affect its performance:
089: * <i>initial capacity</i> and <i>load factor</i>. They are defined precisely
090: * as for <tt>HashMap</tt>. Note, however, that the penalty for choosing an
091: * excessively high value for initial capacity is less severe for this class
092: * than for <tt>HashMap</tt>, as iteration times for this class are unaffected
093: * by capacity.
094: *
095: * <p><strong>Note that this implementation is not synchronized.</strong> If
096: * multiple threads access a linked hash map concurrently, and at least
097: * one of the threads modifies the map structurally, it <em>must</em> be
098: * synchronized externally. This is typically accomplished by synchronizing
099: * on some object that naturally encapsulates the map. If no such object
100: * exists, the map should be "wrapped" using the
101: * <tt>Collections.synchronizedMap</tt>method. This is best done at creation
102: * time, to prevent accidental unsynchronized access:
103: * <pre>
104: * Map m = Collections.synchronizedMap(new LinkedHashMap(...));
105: * </pre>
106: * A structural modification is any operation that adds or deletes one or more
107: * mappings or, in the case of access-ordered linked hash maps, affects
108: * iteration order. In insertion-ordered linked hash maps, merely changing
109: * the value associated with a key that is already contained in the map is not
110: * a structural modification. <strong>In access-ordered linked hash maps,
111: * merely querying the map with <tt>get</tt> is a structural
112: * modification.</strong>)
113: *
114: * <p>The iterators returned by the <tt>iterator</tt> methods of the
115: * collections returned by all of this class's collection view methods are
116: * <em>fail-fast</em>: if the map is structurally modified at any time after
117: * the iterator is created, in any way except through the iterator's own
118: * remove method, the iterator will throw a
119: * <tt>ConcurrentModificationException</tt>. Thus, in the face of concurrent
120: * modification, the Iterator fails quickly and cleanly, rather than risking
121: * arbitrary, non-deterministic behavior at an undetermined time in the
122: * future.
123: *
124: * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
125: * as it is, generally speaking, impossible to make any hard guarantees in the
126: * presence of unsynchronized concurrent modification. Fail-fast iterators
127: * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
128: * Therefore, it would be wrong to write a program that depended on this
129: * exception for its correctness: <i>the fail-fast behavior of iterators
130: * should be used only to detect bugs.</i>
131: *
132: * <p>This class is a member of the
133: * <a href="{@docRoot}/../guide/collections/index.html">
134: * Java Collections Framework</a>.
135: *
136: * @author Josh Bloch
137: * @version 1.14, 10/10/06
138: * @see Object#hashCode()
139: * @see Collection
140: * @see Map
141: * @see HashMap
142: * @see TreeMap
143: * @see Hashtable
144: * @since JDK1.4
145: */
146:
147: public class LinkedHashMap extends HashMap {
148: /**
149: * The head of the doubly linked list.
150: */
151: private transient Entry header;
152:
153: /**
154: * The iteration ordering method for this linked hash map: <tt>true</tt>
155: * for access-order, <tt>false</tt> for insertion-order.
156: *
157: * @serial
158: */
159: private final boolean accessOrder;
160:
161: /**
162: * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
163: * with the specified initial capacity and load factor.
164: *
165: * @param initialCapacity the initial capacity.
166: * @param loadFactor the load factor.
167: * @throws IllegalArgumentException if the initial capacity is negative
168: * or the load factor is nonpositive.
169: */
170: public LinkedHashMap(int initialCapacity, float loadFactor) {
171: super (initialCapacity, loadFactor);
172: accessOrder = false;
173: }
174:
175: /**
176: * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
177: * with the specified initial capacity and a default load factor (0.75).
178: *
179: * @param initialCapacity the initial capacity.
180: * @throws IllegalArgumentException if the initial capacity is negative.
181: */
182: public LinkedHashMap(int initialCapacity) {
183: super (initialCapacity);
184: accessOrder = false;
185: }
186:
187: /**
188: * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
189: * with a default capacity (16) and load factor (0.75).
190: */
191: public LinkedHashMap() {
192: super ();
193: accessOrder = false;
194: }
195:
196: /**
197: * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with
198: * the same mappings as the specified map. The <tt>LinkedHashMap</tt>
199: * instance is created with a a default load factor (0.75) and an initial
200: * capacity sufficient to hold the mappings in the specified map.
201: *
202: * @param m the map whose mappings are to be placed in this map.
203: * @throws NullPointerException if the specified map is null.
204: */
205: public LinkedHashMap(Map m) {
206: super (m);
207: accessOrder = false;
208: }
209:
210: /**
211: * Constructs an empty <tt>LinkedHashMap</tt> instance with the
212: * specified initial capacity, load factor and ordering mode.
213: *
214: * @param initialCapacity the initial capacity.
215: * @param loadFactor the load factor.
216: * @param accessOrder the ordering mode - <tt>true</tt> for
217: * access-order, <tt>false</tt> for insertion-order.
218: * @throws IllegalArgumentException if the initial capacity is negative
219: * or the load factor is nonpositive.
220: */
221: public LinkedHashMap(int initialCapacity, float loadFactor,
222: boolean accessOrder) {
223: super (initialCapacity, loadFactor);
224: this .accessOrder = accessOrder;
225: }
226:
227: /**
228: * Called by superclass constructors and pseudoconstructors (clone,
229: * readObject) before any entries are inserted into the map. Initializes
230: * the chain.
231: */
232: void init() {
233: header = new Entry(-1, null, null, null);
234: header.before = header.after = header;
235: }
236:
237: /**
238: * Transfer all entries to new table array. This method is called
239: * by superclass resize. It is overridden for performance, as it is
240: * faster to iterate using our linked list.
241: */
242: void transfer(HashMap.Entry[] newTable) {
243: int newCapacity = newTable.length;
244: for (Entry e = header.after; e != header; e = e.after) {
245: int index = indexFor(e.hash, newCapacity);
246: e.next = newTable[index];
247: newTable[index] = e;
248: }
249: }
250:
251: /**
252: * Returns <tt>true</tt> if this map maps one or more keys to the
253: * specified value.
254: *
255: * @param value value whose presence in this map is to be tested.
256: * @return <tt>true</tt> if this map maps one or more keys to the
257: * specified value.
258: */
259: public boolean containsValue(Object value) {
260: // Overridden to take advantage of faster iterator
261: if (value == null) {
262: for (Entry e = header.after; e != header; e = e.after)
263: if (e.value == null)
264: return true;
265: } else {
266: for (Entry e = header.after; e != header; e = e.after)
267: if (value.equals(e.value))
268: return true;
269: }
270: return false;
271: }
272:
273: /**
274: * Returns the value to which this map maps the specified key. Returns
275: * <tt>null</tt> if the map contains no mapping for this key. A return
276: * value of <tt>null</tt> does not <i>necessarily</i> indicate that the
277: * map contains no mapping for the key; it's also possible that the map
278: * explicitly maps the key to <tt>null</tt>. The <tt>containsKey</tt>
279: * operation may be used to distinguish these two cases.
280: *
281: * @return the value to which this map maps the specified key.
282: * @param key key whose associated value is to be returned.
283: */
284: public Object get(Object key) {
285: Entry e = (Entry) getEntry(key);
286: if (e == null)
287: return null;
288: e.recordAccess(this );
289: return e.value;
290: }
291:
292: /**
293: * Removes all mappings from this map.
294: */
295: public void clear() {
296: super .clear();
297: header.before = header.after = header;
298: }
299:
300: /**
301: * LinkedHashMap entry.
302: */
303: private static class Entry extends HashMap.Entry {
304: // These fields comprise the doubly linked list used for iteration.
305: Entry before, after;
306:
307: Entry(int hash, Object key, Object value, HashMap.Entry next) {
308: super (hash, key, value, next);
309: }
310:
311: /**
312: * Remove this entry from the linked list.
313: */
314: private void remove() {
315: before.after = after;
316: after.before = before;
317: }
318:
319: /**
320: * Insert this entry before the specified existing entry in the list.
321: */
322: private void addBefore(Entry existingEntry) {
323: after = existingEntry;
324: before = existingEntry.before;
325: before.after = this ;
326: after.before = this ;
327: }
328:
329: /**
330: * This method is invoked by the superclass whenever the value
331: * of a pre-existing entry is read by Map.get or modified by Map.set.
332: * If the enclosing Map is access-ordered, it moves the entry
333: * to the end of the list; otherwise, it does nothing.
334: */
335: void recordAccess(HashMap m) {
336: LinkedHashMap lm = (LinkedHashMap) m;
337: if (lm.accessOrder) {
338: lm.modCount++;
339: remove();
340: addBefore(lm.header);
341: }
342: }
343:
344: void recordRemoval(HashMap m) {
345: remove();
346: }
347: }
348:
349: private abstract class LinkedHashIterator implements Iterator {
350: Entry nextEntry = header.after;
351: Entry lastReturned = null;
352:
353: /**
354: * The modCount value that the iterator believes that the backing
355: * List should have. If this expectation is violated, the iterator
356: * has detected concurrent modification.
357: */
358: int expectedModCount = modCount;
359:
360: public boolean hasNext() {
361: return nextEntry != header;
362: }
363:
364: public void remove() {
365: if (lastReturned == null)
366: throw new IllegalStateException();
367: if (modCount != expectedModCount)
368: throw new ConcurrentModificationException();
369:
370: LinkedHashMap.this .remove(lastReturned.key);
371: lastReturned = null;
372: expectedModCount = modCount;
373: }
374:
375: Entry nextEntry() {
376: if (modCount != expectedModCount)
377: throw new ConcurrentModificationException();
378: if (nextEntry == header)
379: throw new NoSuchElementException();
380:
381: Entry e = lastReturned = nextEntry;
382: nextEntry = e.after;
383: return e;
384: }
385: }
386:
387: private class KeyIterator extends LinkedHashIterator {
388: public Object next() {
389: return nextEntry().getKey();
390: }
391: }
392:
393: private class ValueIterator extends LinkedHashIterator {
394: public Object next() {
395: return nextEntry().value;
396: }
397: }
398:
399: private class EntryIterator extends LinkedHashIterator {
400: public Object next() {
401: return nextEntry();
402: }
403: }
404:
405: // These Overrides alter the behavior of superclass view iterator() methods
406: Iterator newKeyIterator() {
407: return new KeyIterator();
408: }
409:
410: Iterator newValueIterator() {
411: return new ValueIterator();
412: }
413:
414: Iterator newEntryIterator() {
415: return new EntryIterator();
416: }
417:
418: /**
419: * This override alters behavior of superclass put method. It causes newly
420: * allocated entry to get inserted at the end of the linked list and
421: * removes the eldest entry if appropriate.
422: */
423: void addEntry(int hash, Object key, Object value, int bucketIndex) {
424: createEntry(hash, key, value, bucketIndex);
425:
426: // Remove eldest entry if instructed, else grow capacity if appropriate
427: Entry eldest = header.after;
428: if (removeEldestEntry(eldest)) {
429: removeEntryForKey(eldest.key);
430: } else {
431: if (size >= threshold)
432: resize(2 * table.length);
433: }
434: }
435:
436: /**
437: * This override differs from addEntry in that it doesn't resize the
438: * table or remove the eldest entry.
439: */
440: void createEntry(int hash, Object key, Object value, int bucketIndex) {
441: Entry e = new Entry(hash, key, value, table[bucketIndex]);
442: table[bucketIndex] = e;
443: e.addBefore(header);
444: size++;
445: }
446:
447: /**
448: * Returns <tt>true</tt> if this map should remove its eldest entry.
449: * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
450: * inserting a new entry into the map. It provides the implementer
451: * with the opportunity to remove the eldest entry each time a new one
452: * is added. This is useful if the map represents a cache: it allows
453: * the map to reduce memory consumption by deleting stale entries.
454: *
455: * <p>Sample use: this override will allow the map to grow up to 100
456: * entries and then delete the eldest entry each time a new entry is
457: * added, maintaining a steady state of 100 entries.
458: * <pre>
459: * private static final int MAX_ENTRIES = 100;
460: *
461: * protected boolean removeEldestEntry(Map.Entry eldest) {
462: * return size() > MAX_ENTRIES;
463: * }
464: * </pre>
465: *
466: * <p>This method typically does not modify the map in any way,
467: * instead allowing the map to modify itself as directed by its
468: * return value. It <i>is</i> permitted for this method to modify
469: * the map directly, but if it does so, it <i>must</i> return
470: * <tt>false</tt> (indicating that the map should not attempt any
471: * further modification). The effects of returning <tt>true</tt>
472: * after modifying the map from within this method are unspecified.
473: *
474: * <p>This implementation merely returns <tt>false</tt> (so that this
475: * map acts like a normal map - the eldest element is never removed).
476: *
477: * @param eldest The least recently inserted entry in the map, or if
478: * this is an access-ordered map, the least recently accessed
479: * entry. This is the entry that will be removed it this
480: * method returns <tt>true</tt>. If the map was empty prior
481: * to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
482: * in this invocation, this will be the entry that was just
483: * inserted; in other words, if the map contains a single
484: * entry, the eldest entry is also the newest.
485: * @return <tt>true</tt> if the eldest entry should be removed
486: * from the map; <tt>false</t> if it should be retained.
487: */
488: protected boolean removeEldestEntry(Map.Entry eldest) {
489: return false;
490: }
491: }
|