LinkedHashMap.java 16 KB

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