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