KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > util > LinkedHashMap


1 /*
2  * @(#)LinkedHashMap.java 1.18 04/02/19
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.util;
9 import java.io.*;
10
11 /**
12  * <p>Hash table and linked list implementation of the <tt>Map</tt> interface,
13  * with predictable iteration order. This implementation differs from
14  * <tt>HashMap</tt> in that it maintains a doubly-linked list running through
15  * all of its entries. This linked list defines the iteration ordering,
16  * which is normally the order in which keys were inserted into the map
17  * (<i>insertion-order</i>). Note that insertion order is not affected
18  * if a key is <i>re-inserted</i> into the map. (A key <tt>k</tt> is
19  * reinserted into a map <tt>m</tt> if <tt>m.put(k, v)</tt> is invoked when
20  * <tt>m.containsKey(k)</tt> would return <tt>true</tt> immediately prior to
21  * the invocation.)
22  *
23  * <p>This implementation spares its clients from the unspecified, generally
24  * chaotic ordering provided by {@link HashMap} (and {@link Hashtable}),
25  * without incurring the increased cost associated with {@link TreeMap}. It
26  * can be used to produce a copy of a map that has the same order as the
27  * original, regardless of the original map's implementation:
28  * <pre>
29  * void foo(Map m) {
30  * Map copy = new LinkedHashMap(m);
31  * ...
32  * }
33  * </pre>
34  * This technique is particularly useful if a module takes a map on input,
35  * copies it, and later returns results whose order is determined by that of
36  * the copy. (Clients generally appreciate having things returned in the same
37  * order they were presented.)
38  *
39  * <p>A special {@link #LinkedHashMap(int,float,boolean) constructor} is
40  * provided to create a linked hash map whose order of iteration is the order
41  * in which its entries were last accessed, from least-recently accessed to
42  * most-recently (<i>access-order</i>). This kind of map is well-suited to
43  * building LRU caches. Invoking the <tt>put</tt> or <tt>get</tt> method
44  * results in an access to the corresponding entry (assuming it exists after
45  * the invocation completes). The <tt>putAll</tt> method generates one entry
46  * access for each mapping in the specified map, in the order that key-value
47  * mappings are provided by the specified map's entry set iterator. <i>No
48  * other methods generate entry accesses.</i> In particular, operations on
49  * collection-views do <i>not</i> affect the order of iteration of the backing
50  * map.
51  *
52  * <p>The {@link #removeEldestEntry(Map.Entry)} method may be overridden to
53  * impose a policy for removing stale mappings automatically when new mappings
54  * are added to the map.
55  *
56  * <p>This class provides all of the optional <tt>Map</tt> operations, and
57  * permits null elements. Like <tt>HashMap</tt>, it provides constant-time
58  * performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and
59  * <tt>remove</tt>), assuming the hash function disperses elements
60  * properly among the buckets. Performance is likely to be just slightly
61  * below that of <tt>HashMap</tt>, due to the added expense of maintaining the
62  * linked list, with one exception: Iteration over the collection-views
63  * of a <tt>LinkedHashMap</tt> requires time proportional to the <i>size</i>
64  * of the map, regardless of its capacity. Iteration over a <tt>HashMap</tt>
65  * is likely to be more expensive, requiring time proportional to its
66  * <i>capacity</i>.
67  *
68  * <p>A linked hash map has two parameters that affect its performance:
69  * <i>initial capacity</i> and <i>load factor</i>. They are defined precisely
70  * as for <tt>HashMap</tt>. Note, however, that the penalty for choosing an
71  * excessively high value for initial capacity is less severe for this class
72  * than for <tt>HashMap</tt>, as iteration times for this class are unaffected
73  * by capacity.
74  *
75  * <p><strong>Note that this implementation is not synchronized.</strong> If
76  * multiple threads access a linked hash map concurrently, and at least
77  * one of the threads modifies the map structurally, it <em>must</em> be
78  * synchronized externally. This is typically accomplished by synchronizing
79  * on some object that naturally encapsulates the map. If no such object
80  * exists, the map should be "wrapped" using the
81  * <tt>Collections.synchronizedMap</tt>method. This is best done at creation
82  * time, to prevent accidental unsynchronized access:
83  * <pre>
84  * Map m = Collections.synchronizedMap(new LinkedHashMap(...));
85  * </pre>
86  * A structural modification is any operation that adds or deletes one or more
87  * mappings or, in the case of access-ordered linked hash maps, affects
88  * iteration order. In insertion-ordered linked hash maps, merely changing
89  * the value associated with a key that is already contained in the map is not
90  * a structural modification. <strong>In access-ordered linked hash maps,
91  * merely querying the map with <tt>get</tt> is a structural
92  * modification.</strong>)
93  *
94  * <p>The iterators returned by the <tt>iterator</tt> methods of the
95  * collections returned by all of this class's collection view methods are
96  * <em>fail-fast</em>: if the map is structurally modified at any time after
97  * the iterator is created, in any way except through the iterator's own
98  * remove method, the iterator will throw a
99  * <tt>ConcurrentModificationException</tt>. Thus, in the face of concurrent
100  * modification, the Iterator fails quickly and cleanly, rather than risking
101  * arbitrary, non-deterministic behavior at an undetermined time in the
102  * future.
103  *
104  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
105  * as it is, generally speaking, impossible to make any hard guarantees in the
106  * presence of unsynchronized concurrent modification. Fail-fast iterators
107  * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
108  * Therefore, it would be wrong to write a program that depended on this
109  * exception for its correctness: <i>the fail-fast behavior of iterators
110  * should be used only to detect bugs.</i>
111  *
112  * <p>This class is a member of the
113  * <a HREF="{@docRoot}/../guide/collections/index.html">
114  * Java Collections Framework</a>.
115  *
116  * @author Josh Bloch
117  * @version 1.18, 02/19/04
118  * @see Object#hashCode()
119  * @see Collection
120  * @see Map
121  * @see HashMap
122  * @see TreeMap
123  * @see Hashtable
124  * @since JDK1.4
125  */

126
127 public class LinkedHashMap<K,V>
128     extends HashMap JavaDoc<K,V>
129     implements Map JavaDoc<K,V>
130 {
131
132     private static final long serialVersionUID = 3801124242820219131L;
133
134     /**
135      * The head of the doubly linked list.
136      */

137     private transient Entry<K,V> header;
138
139     /**
140      * The iteration ordering method for this linked hash map: <tt>true</tt>
141      * for access-order, <tt>false</tt> for insertion-order.
142      *
143      * @serial
144      */

145     private final boolean accessOrder;
146
147     /**
148      * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
149      * with the specified initial capacity and load factor.
150      *
151      * @param initialCapacity the initial capacity.
152      * @param loadFactor the load factor.
153      * @throws IllegalArgumentException if the initial capacity is negative
154      * or the load factor is nonpositive.
155      */

156     public LinkedHashMap(int initialCapacity, float loadFactor) {
157         super(initialCapacity, loadFactor);
158         accessOrder = false;
159     }
160
161     /**
162      * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
163      * with the specified initial capacity and a default load factor (0.75).
164      *
165      * @param initialCapacity the initial capacity.
166      * @throws IllegalArgumentException if the initial capacity is negative.
167      */

168     public LinkedHashMap(int initialCapacity) {
169     super(initialCapacity);
170         accessOrder = false;
171     }
172
173     /**
174      * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
175      * with a default capacity (16) and load factor (0.75).
176      */

177     public LinkedHashMap() {
178     super();
179         accessOrder = false;
180     }
181
182     /**
183      * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with
184      * the same mappings as the specified map. The <tt>LinkedHashMap</tt>
185      * instance is created with a a default load factor (0.75) and an initial
186      * capacity sufficient to hold the mappings in the specified map.
187      *
188      * @param m the map whose mappings are to be placed in this map.
189      * @throws NullPointerException if the specified map is null.
190      */

191     public LinkedHashMap(Map JavaDoc<? extends K, ? extends V> m) {
192         super(m);
193         accessOrder = false;
194     }
195
196     /**
197      * Constructs an empty <tt>LinkedHashMap</tt> instance with the
198      * specified initial capacity, load factor and ordering mode.
199      *
200      * @param initialCapacity the initial capacity.
201      * @param loadFactor the load factor.
202      * @param accessOrder the ordering mode - <tt>true</tt> for
203      * access-order, <tt>false</tt> for insertion-order.
204      * @throws IllegalArgumentException if the initial capacity is negative
205      * or the load factor is nonpositive.
206      */

207     public LinkedHashMap(int initialCapacity,
208              float loadFactor,
209                          boolean accessOrder) {
210         super(initialCapacity, loadFactor);
211         this.accessOrder = accessOrder;
212     }
213
214     /**
215      * Called by superclass constructors and pseudoconstructors (clone,
216      * readObject) before any entries are inserted into the map. Initializes
217      * the chain.
218      */

219     void init() {
220         header = new Entry<K,V>(-1, null, null, null);
221         header.before = header.after = header;
222     }
223
224     /**
225      * Transfer all entries to new table array. This method is called
226      * by superclass resize. It is overridden for performance, as it is
227      * faster to iterate using our linked list.
228      */

229     void transfer(HashMap.Entry JavaDoc[] newTable) {
230         int newCapacity = newTable.length;
231         for (Entry<K,V> e = header.after; e != header; e = e.after) {
232             int index = indexFor(e.hash, newCapacity);
233             e.next = newTable[index];
234             newTable[index] = e;
235         }
236     }
237
238
239     /**
240      * Returns <tt>true</tt> if this map maps one or more keys to the
241      * specified value.
242      *
243      * @param value value whose presence in this map is to be tested.
244      * @return <tt>true</tt> if this map maps one or more keys to the
245      * specified value.
246      */

247     public boolean containsValue(Object JavaDoc value) {
248         // Overridden to take advantage of faster iterator
249
if (value==null) {
250             for (Entry e = header.after; e != header; e = e.after)
251                 if (e.value==null)
252                     return true;
253         } else {
254             for (Entry e = header.after; e != header; e = e.after)
255                 if (value.equals(e.value))
256                     return true;
257         }
258         return false;
259     }
260
261     /**
262      * Returns the value to which this map maps the specified key. Returns
263      * <tt>null</tt> if the map contains no mapping for this key. A return
264      * value of <tt>null</tt> does not <i>necessarily</i> indicate that the
265      * map contains no mapping for the key; it's also possible that the map
266      * explicitly maps the key to <tt>null</tt>. The <tt>containsKey</tt>
267      * operation may be used to distinguish these two cases.
268      *
269      * @return the value to which this map maps the specified key.
270      * @param key key whose associated value is to be returned.
271      */

272     public V get(Object JavaDoc key) {
273         Entry<K,V> e = (Entry<K,V>)getEntry(key);
274         if (e == null)
275             return null;
276         e.recordAccess(this);
277         return e.value;
278     }
279
280     /**
281      * Removes all mappings from this map.
282      */

283     public void clear() {
284         super.clear();
285         header.before = header.after = header;
286     }
287
288     /**
289      * LinkedHashMap entry.
290      */

291     private static class Entry<K,V> extends HashMap.Entry JavaDoc<K,V> {
292         // These fields comprise the doubly linked list used for iteration.
293
Entry<K,V> before, after;
294
295     Entry(int hash, K key, V value, HashMap.Entry JavaDoc<K,V> next) {
296             super(hash, key, value, next);
297         }
298
299         /**
300          * Remove this entry from the linked list.
301          */

302         private void remove() {
303             before.after = after;
304             after.before = before;
305         }
306
307         /**
308          * Insert this entry before the specified existing entry in the list.
309          */

310         private void addBefore(Entry<K,V> existingEntry) {
311             after = existingEntry;
312             before = existingEntry.before;
313             before.after = this;
314             after.before = this;
315         }
316
317         /**
318          * This method is invoked by the superclass whenever the value
319          * of a pre-existing entry is read by Map.get or modified by Map.set.
320          * If the enclosing Map is access-ordered, it moves the entry
321          * to the end of the list; otherwise, it does nothing.
322          */

323         void recordAccess(HashMap JavaDoc<K,V> m) {
324             LinkedHashMap JavaDoc<K,V> lm = (LinkedHashMap JavaDoc<K,V>)m;
325             if (lm.accessOrder) {
326                 lm.modCount++;
327                 remove();
328                 addBefore(lm.header);
329             }
330         }
331
332         void recordRemoval(HashMap JavaDoc<K,V> m) {
333             remove();
334         }
335     }
336
337     private abstract class LinkedHashIterator<T> implements Iterator JavaDoc<T> {
338     Entry<K,V> nextEntry = header.after;
339     Entry<K,V> lastReturned = null;
340
341     /**
342      * The modCount value that the iterator believes that the backing
343      * List should have. If this expectation is violated, the iterator
344      * has detected concurrent modification.
345      */

346     int expectedModCount = modCount;
347
348     public boolean hasNext() {
349             return nextEntry != header;
350     }
351
352     public void remove() {
353         if (lastReturned == null)
354         throw new IllegalStateException JavaDoc();
355         if (modCount != expectedModCount)
356         throw new ConcurrentModificationException JavaDoc();
357
358             LinkedHashMap.this.remove(lastReturned.key);
359             lastReturned = null;
360             expectedModCount = modCount;
361     }
362
363     Entry<K,V> nextEntry() {
364         if (modCount != expectedModCount)
365         throw new ConcurrentModificationException JavaDoc();
366             if (nextEntry == header)
367                 throw new NoSuchElementException JavaDoc();
368
369             Entry<K,V> e = lastReturned = nextEntry;
370             nextEntry = e.after;
371             return e;
372     }
373     }
374
375     private class KeyIterator extends LinkedHashIterator<K> {
376     public K next() { return nextEntry().getKey(); }
377     }
378
379     private class ValueIterator extends LinkedHashIterator<V> {
380     public V next() { return nextEntry().value; }
381     }
382
383     private class EntryIterator extends LinkedHashIterator<Map.Entry JavaDoc<K,V>> {
384     public Map.Entry JavaDoc<K,V> next() { return nextEntry(); }
385     }
386
387     // These Overrides alter the behavior of superclass view iterator() methods
388
Iterator JavaDoc<K> newKeyIterator() { return new KeyIterator(); }
389     Iterator JavaDoc<V> newValueIterator() { return new ValueIterator(); }
390     Iterator JavaDoc<Map.Entry JavaDoc<K,V>> newEntryIterator() { return new EntryIterator(); }
391
392     /**
393      * This override alters behavior of superclass put method. It causes newly
394      * allocated entry to get inserted at the end of the linked list and
395      * removes the eldest entry if appropriate.
396      */

397     void addEntry(int hash, K key, V value, int bucketIndex) {
398         createEntry(hash, key, value, bucketIndex);
399
400         // Remove eldest entry if instructed, else grow capacity if appropriate
401
Entry<K,V> eldest = header.after;
402         if (removeEldestEntry(eldest)) {
403             removeEntryForKey(eldest.key);
404         } else {
405             if (size >= threshold)
406                 resize(2 * table.length);
407         }
408     }
409
410     /**
411      * This override differs from addEntry in that it doesn't resize the
412      * table or remove the eldest entry.
413      */

414     void createEntry(int hash, K key, V value, int bucketIndex) {
415         HashMap.Entry JavaDoc<K,V> old = table[bucketIndex];
416     Entry<K,V> e = new Entry<K,V>(hash, key, value, old);
417         table[bucketIndex] = e;
418         e.addBefore(header);
419         size++;
420     }
421
422     /**
423      * Returns <tt>true</tt> if this map should remove its eldest entry.
424      * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
425      * inserting a new entry into the map. It provides the implementer
426      * with the opportunity to remove the eldest entry each time a new one
427      * is added. This is useful if the map represents a cache: it allows
428      * the map to reduce memory consumption by deleting stale entries.
429      *
430      * <p>Sample use: this override will allow the map to grow up to 100
431      * entries and then delete the eldest entry each time a new entry is
432      * added, maintaining a steady state of 100 entries.
433      * <pre>
434      * private static final int MAX_ENTRIES = 100;
435      *
436      * protected boolean removeEldestEntry(Map.Entry eldest) {
437      * return size() > MAX_ENTRIES;
438      * }
439      * </pre>
440      *
441      * <p>This method typically does not modify the map in any way,
442      * instead allowing the map to modify itself as directed by its
443      * return value. It <i>is</i> permitted for this method to modify
444      * the map directly, but if it does so, it <i>must</i> return
445      * <tt>false</tt> (indicating that the map should not attempt any
446      * further modification). The effects of returning <tt>true</tt>
447      * after modifying the map from within this method are unspecified.
448      *
449      * <p>This implementation merely returns <tt>false</tt> (so that this
450      * map acts like a normal map - the eldest element is never removed).
451      *
452      * @param eldest The least recently inserted entry in the map, or if
453      * this is an access-ordered map, the least recently accessed
454      * entry. This is the entry that will be removed it this
455      * method returns <tt>true</tt>. If the map was empty prior
456      * to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
457      * in this invocation, this will be the entry that was just
458      * inserted; in other words, if the map contains a single
459      * entry, the eldest entry is also the newest.
460      * @return <tt>true</tt> if the eldest entry should be removed
461      * from the map; <tt>false</t> if it should be retained.
462      */

463     protected boolean removeEldestEntry(Map.Entry JavaDoc<K,V> eldest) {
464         return false;
465     }
466 }
467
Popular Tags