source: trunk/src/gcc/libjava/java/util/LinkedHashMap.java@ 3

Last change on this file since 3 was 2, checked in by bird, 23 years ago

Initial revision

  • Property cvs2svn:cvs-rev set to 1.1
  • Property svn:eol-style set to native
  • Property svn:executable set to *
File size: 15.4 KB
Line 
1/* LinkedHashMap.java -- a class providing hashtable data structure,
2 mapping Object --> Object, with linked list traversal
3 Copyright (C) 2001 Free Software Foundation, Inc.
4
5This file is part of GNU Classpath.
6
7GNU Classpath is free software; you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
9the Free Software Foundation; either version 2, or (at your option)
10any later version.
11
12GNU Classpath is distributed in the hope that it will be useful, but
13WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with GNU Classpath; see the file COPYING. If not, write to the
19Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
2002111-1307 USA.
21
22Linking this library statically or dynamically with other modules is
23making a combined work based on this library. Thus, the terms and
24conditions of the GNU General Public License cover the whole
25combination.
26
27As a special exception, the copyright holders of this library give you
28permission to link this library with independent modules to produce an
29executable, regardless of the license terms of these independent
30modules, and to copy and distribute the resulting executable under
31terms of your choice, provided that you also meet, for each linked
32independent module, the terms and conditions of the license of that
33module. An independent module is a module which is not derived from
34or based on this library. If you modify this library, you may extend
35this exception to your version of the library, but you are not
36obligated to do so. If you do not wish to do so, delete this
37exception statement from your version. */
38
39
40package java.util;
41
42/**
43 * This class provides a hashtable-backed implementation of the
44 * Map interface, with predictable traversal order.
45 * <p>
46 *
47 * It uses a hash-bucket approach; that is, hash collisions are handled
48 * by linking the new node off of the pre-existing node (or list of
49 * nodes). In this manner, techniques such as linear probing (which
50 * can cause primary clustering) and rehashing (which does not fit very
51 * well with Java's method of precomputing hash codes) are avoided. In
52 * addition, this maintains a doubly-linked list which tracks either
53 * insertion or access order. Note that the insertion order is not
54 * modified if a <code>put</code> simply reinserts a key in the map.
55 * <p>
56 *
57 * One of the nice features of tracking insertion order is that you can
58 * copy a hashtable, and regardless of the implementation of the original,
59 * produce the same results when iterating over the copy. This is possible
60 * without needing the overhead of <code>TreeMap</code>.
61 * <p>
62 *
63 * When using this {@link #LinkedHashMap(int, float, boolean) constructor},
64 * you build an access-order mapping. This can be used to implement LRU
65 * caches, for example. In this case, every invocation of <code>put</code>,
66 * <code>putAll</code>, or <code>get</code> moves the accessed entry to
67 * the end of the iteration list. By overriding
68 * {@link #removeEldestEntry(Map.Entry)}, you can also control the
69 * removal of the oldest entry, and thereby do things like keep the map
70 * at a fixed size.
71 * <p>
72 *
73 * Under ideal circumstances (no collisions), LinkedHashMap offers O(1)
74 * performance on most operations (<pre>containsValue()</pre> is,
75 * of course, O(n)). In the worst case (all keys map to the same
76 * hash code -- very unlikely), most operations are O(n).
77 * <p>
78 *
79 * LinkedHashMap accepts the null key and null values. It is not
80 * synchronized, so if you need multi-threaded access, consider using:<br>
81 * <code>Map m = Collections.synchronizedMap(new LinkedHashMap(...));</code>
82 * <p>
83 *
84 * The iterators are <i>fail-fast</i>, meaning that any structural
85 * modification, except for <code>remove()</code> called on the iterator
86 * itself, cause the iterator to throw a
87 * {@link ConcurrentModificationException} rather than exhibit
88 * non-deterministic behavior.
89 *
90 * @author Eric Blake <[email protected]>
91 * @see Object#hashCode()
92 * @see Collection
93 * @see Map
94 * @see HashMap
95 * @see TreeMap
96 * @see Hashtable
97 * @since 1.4
98 * @status updated to 1.4
99 */
100public class LinkedHashMap extends HashMap
101{
102 /**
103 * Compatible with JDK 1.4.
104 */
105 private static final long serialVersionUID = 3801124242820219131L;
106
107 /**
108 * The first Entry to iterate over.
109 */
110 transient LinkedHashEntry head;
111
112 /**
113 * The last Entry to iterate over.
114 */
115 transient LinkedHashEntry tail;
116
117 /**
118 * The iteration order of this linked hash map: <code>true</code> for
119 * access-order, <code>false</code> for insertion-order.
120 * @serial
121 */
122 final boolean accessOrder;
123
124 /**
125 * Class to represent an entry in the hash table. Holds a single key-value
126 * pair and the doubly-linked insertion order list.
127 */
128 class LinkedHashEntry extends HashEntry
129 {
130 /** The predecessor in the iteration list, null if this is the eldest. */
131 LinkedHashEntry pred;
132 /** The successor in the iteration list, null if this is the newest. */
133 LinkedHashEntry succ;
134
135 /**
136 * Simple constructor.
137 * @param key the key
138 * @param value the value
139 */
140 LinkedHashEntry(Object key, Object value)
141 {
142 super(key, value);
143 if (head == null)
144 head = this;
145 pred = tail;
146 tail = this;
147 if (pred != null)
148 pred.succ = this;
149 }
150
151 /**
152 * Sets the value of this entry, and shuffles it to the end of
153 * the list if this is in access-order.
154 * @param value the new value
155 * @return the prior value
156 */
157 public Object setValue(Object value)
158 {
159 if (accessOrder && succ != null)
160 {
161 succ.pred = pred;
162 if (pred == null)
163 head = succ;
164 else
165 pred.succ = succ;
166 succ = null;
167 pred = tail;
168 pred.succ = this;
169 tail = this;
170 }
171 return super.setValue(value);
172 }
173
174 /**
175 * Called when this entry is removed from the map. This version does
176 * the necessary bookkeeping to keep the doubly-linked list in order.
177 * @return the value of this key as it is removed
178 */
179 Object cleanup()
180 {
181 if (pred == null)
182 head = succ;
183 else
184 pred.succ = succ;
185 if (succ == null)
186 tail = pred;
187 else
188 succ.pred = pred;
189
190 return value;
191 }
192 }
193
194 /**
195 * Construct a new insertion-ordered LinkedHashMap with the default
196 * capacity (11) and the default load factor (0.75).
197 */
198 public LinkedHashMap()
199 {
200 super();
201 accessOrder = false;
202 }
203
204 /**
205 * Construct a new insertion-ordered LinkedHashMap from the given Map,
206 * with initial capacity the greater of the size of <code>m</code> or
207 * the default of 11.
208 * <p>
209 *
210 * Every element in Map m will be put into this new HashMap, in the
211 * order of m's iterator.
212 *
213 * @param m a Map whose key / value pairs will be put into
214 * the new HashMap. <b>NOTE: key / value pairs
215 * are not cloned in this constructor.</b>
216 * @throws NullPointerException if m is null
217 */
218 public LinkedHashMap(Map m)
219 {
220 super(m);
221 accessOrder = false;
222 }
223
224 /**
225 * Construct a new insertion-ordered LinkedHashMap with a specific
226 * inital capacity and default load factor of 0.75.
227 *
228 * @param initialCapacity the initial capacity of this HashMap (&gt;= 0)
229 * @throws IllegalArgumentException if (initialCapacity &lt; 0)
230 */
231 public LinkedHashMap(int initialCapacity)
232 {
233 super(initialCapacity);
234 accessOrder = false;
235 }
236
237 /**
238 * Construct a new insertion-orderd LinkedHashMap with a specific
239 * inital capacity and load factor.
240 *
241 * @param initialCapacity the initial capacity (&gt;= 0)
242 * @param loadFactor the load factor (&gt; 0, not NaN)
243 * @throws IllegalArgumentException if (initialCapacity &lt; 0) ||
244 * ! (loadFactor &gt; 0.0)
245 */
246 public LinkedHashMap(int initialCapacity, float loadFactor)
247 {
248 super(initialCapacity, loadFactor);
249 accessOrder = false;
250 }
251
252 /**
253 * Construct a new LinkedHashMap with a specific inital capacity, load
254 * factor, and ordering mode.
255 *
256 * @param initialCapacity the initial capacity (>=0)
257 * @param loadFactor the load factor (>0, not NaN)
258 * @param accessOrder true for access-order, false for insertion-order
259 * @throws IllegalArgumentException if (initialCapacity < 0) ||
260 * ! (loadFactor > 0.0)
261 */
262 public LinkedHashMap(int initialCapacity, float loadFactor,
263 boolean accessOrder)
264 {
265 super(initialCapacity, loadFactor);
266 this.accessOrder = accessOrder;
267 }
268
269 /**
270 * Clears the Map so it has no keys. This is O(1).
271 */
272 public void clear()
273 {
274 super.clear();
275 head = null;
276 tail = null;
277 }
278
279 /**
280 * Returns true if this HashMap contains a value <pre>o</pre>, such that
281 * <pre>o.equals(value)</pre>.
282 *
283 * @param value the value to search for in this HashMap
284 * @return true if at least one key maps to the value
285 */
286 public boolean containsValue(Object value)
287 {
288 LinkedHashEntry e = head;
289 while (e != null)
290 {
291 if (equals(value, e.value))
292 return true;
293 e = e.succ;
294 }
295 return false;
296 }
297
298 /**
299 * Return the value in this Map associated with the supplied key,
300 * or <pre>null</pre> if the key maps to nothing. If this is an
301 * access-ordered Map and the key is found, this performs structural
302 * modification, moving the key to the newest end of the list. NOTE:
303 * Since the value could also be null, you must use containsKey to
304 * see if this key actually maps to something.
305 *
306 * @param key the key for which to fetch an associated value
307 * @return what the key maps to, if present
308 * @see #put(Object, Object)
309 * @see #containsKey(Object)
310 */
311 public Object get(Object key)
312 {
313 int idx = hash(key);
314 HashEntry e = buckets[idx];
315 while (e != null)
316 {
317 if (equals(key, e.key))
318 {
319 if (accessOrder)
320 {
321 modCount++;
322 LinkedHashEntry l = (LinkedHashEntry) e;
323 if (l.succ != null)
324 {
325 l.succ.pred = l.pred;
326 if (l.pred == null)
327 head = l.succ;
328 else
329 l.pred.succ = l.succ;
330 l.succ = null;
331 l.pred = tail;
332 tail.succ = l;
333 tail = l;
334 }
335 }
336 return e.value;
337 }
338 e = e.next;
339 }
340 return null;
341 }
342
343 /**
344 * Returns <code>true</code> if this map should remove the eldest entry.
345 * This method is invoked by all calls to <code>put</code> and
346 * <code>putAll</code> which place a new entry in the map, providing
347 * the implementer an opportunity to remove the eldest entry any time
348 * a new one is added. This can be used to save memory usage of the
349 * hashtable, as well as emulating a cache, by deleting stale entries.
350 * <p>
351 *
352 * For example, to keep the Map limited to 100 entries, override as follows:
353 * <pre>
354 * private static final int MAX_ENTRIES = 100;
355 *
356 * protected boolean removeEldestEntry(Map.Entry eldest)
357 * {
358 * return size() > MAX_ENTRIES;
359 * }
360 * </pre><p>
361 *
362 * Typically, this method does not modify the map, but just uses the
363 * return value as an indication to <code>put</code> whether to proceed.
364 * However, if you override it to modify the map, you must return false
365 * (indicating that <code>put</code> should do nothing), or face
366 * unspecified behavior.
367 * <p>
368 *
369 * This method is called after the eldest entry has been inserted, so
370 * if <code>put</code> was called on a previously empty map, the eldest
371 * entry is the one you just put in! The default implementation just
372 * returns <code>false</code>, so that this map always behaves like
373 * a normal one with unbounded growth.
374 *
375 * @param eldest the eldest element which would be removed if this
376 * returns true. For an access-order map, this is the least
377 * recently accessed; for an insertion-order map, this is the
378 * earliest element inserted.
379 * @return true if <code>eldest</code> should be removed
380 */
381 protected boolean removeEldestEntry(Map.Entry eldest)
382 {
383 return false;
384 }
385
386 /**
387 * Helper method called by <code>put</code>, which creates and adds a
388 * new Entry, followed by performing bookkeeping (like removeEldestEntry).
389 *
390 * @param key the key of the new Entry
391 * @param value the value
392 * @param idx the index in buckets where the new Entry belongs
393 * @param callRemove whether to call the removeEldestEntry method
394 * @see #put(Object, Object)
395 * @see #removeEldestEntry(Map.Entry)
396 */
397 void addEntry(Object key, Object value, int idx, boolean callRemove)
398 {
399 LinkedHashEntry e = new LinkedHashEntry(key, value);
400
401 e.next = buckets[idx];
402 buckets[idx] = e;
403
404 if (callRemove && removeEldestEntry(head))
405 remove(head);
406 }
407
408 /**
409 * Helper method, called by clone() to reset the doubly-linked list.
410 * @param m the map to add entries from
411 * @see #clone()
412 */
413 void putAllInternal(Map m)
414 {
415 head = null;
416 tail = null;
417 super.putAllInternal(m);
418 }
419
420 /**
421 * Generates a parameterized iterator. This allows traversal to follow
422 * the doubly-linked list instead of the random bin order of HashMap.
423 * @param type {@link #KEYS}, {@link #VALUES}, or {@link #ENTRIES}
424 * @return the appropriate iterator
425 */
426 Iterator iterator(final int type)
427 {
428 return new Iterator()
429 {
430 /** The current Entry */
431 LinkedHashEntry current = head;
432
433 /** The previous Entry returned by next() */
434 LinkedHashEntry last;
435
436 /** The number of known modifications to the backing HashMap */
437 int knownMod = modCount;
438
439 /**
440 * Returns true if the Iterator has more elements.
441 * @return true if there are more elements
442 * @throws ConcurrentModificationException if the HashMap was modified
443 */
444 public boolean hasNext()
445 {
446 if (knownMod != modCount)
447 throw new ConcurrentModificationException();
448 return current != null;
449 }
450
451 /**
452 * Returns the next element in the Iterator's sequential view.
453 * @return the next element
454 * @throws ConcurrentModificationException if the HashMap was modified
455 * @throws NoSuchElementException if there is none
456 */
457 public Object next()
458 {
459 if (knownMod != modCount)
460 throw new ConcurrentModificationException();
461 if (current == null)
462 throw new NoSuchElementException();
463 last = current;
464 current = current.succ;
465 return type == VALUES ? last.value : type == KEYS ? last.key : last;
466 }
467
468 /**
469 * Removes from the backing HashMap the last element which was fetched
470 * with the <pre>next()</pre> method.
471 * @throws ConcurrentModificationException if the HashMap was modified
472 * @throws IllegalStateException if called when there is no last element
473 */
474 public void remove()
475 {
476 if (knownMod != modCount)
477 throw new ConcurrentModificationException();
478 if (last == null)
479 throw new IllegalStateException();
480
481 LinkedHashMap.this.remove(last.key);
482 last = null;
483 knownMod++;
484 }
485 };
486 }
487}
Note: See TracBrowser for help on using the repository browser.