1. /*
  2. * @(#)LinkedHashMap.java 1.11 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util;
  8. import java.io.*;
  9. /**
  10. * <p>Hash table and linked list implementation of the <tt>Map</tt> interface,
  11. * with predictable iteration order. This implementation differs from
  12. * <tt>HashMap</tt> in that it maintains a doubly-linked list running through
  13. * all of its entries. This linked list defines the iteration ordering,
  14. * which is normally the order in which keys were inserted into the map
  15. * (<i>insertion-order</i>). Note that insertion order is not affected
  16. * if a key is <i>re-inserted</i> into the map. (A key <tt>k</tt> is
  17. * reinserted into a map <tt>m</tt> if <tt>m.put(k, v)</tt> is invoked when
  18. * <tt>m.containsKey(k)</tt> would return <tt>true</tt> immediately prior to
  19. * the invocation.)
  20. *
  21. * <p>This implementation spares its clients from the unspecified, generally
  22. * chaotic ordering provided by {@link HashMap} (and {@link Hashtable}),
  23. * without incurring the increased cost associated with {@link TreeMap}. It
  24. * can be used to produce a copy of a map that has the same order as the
  25. * original, regardless of the original map's implementation:
  26. * <pre>
  27. * void foo(Map m) {
  28. * Map copy = new LinkedHashMap(m);
  29. * ...
  30. * }
  31. * </pre>
  32. * This technique is particularly useful if a module takes a map on input,
  33. * copies it, and later returns results whose order is determined by that of
  34. * the copy. (Clients generally appreciate having things returned in the same
  35. * order they were presented.)
  36. *
  37. * <p>A special {@link #LinkedHashMap(int,float,boolean) constructor} is
  38. * provided to create a linked hash map whose order of iteration is the order
  39. * in which its entries were last accessed, from least-recently accessed to
  40. * most-recently (<i>access-order</i>). This kind of map is well-suited to
  41. * building LRU caches. Invoking the <tt>put</tt> or <tt>get</tt> method
  42. * results in an access to the corresponding entry (assuming it exists after
  43. * the invocation completes). The <tt>putAll</tt> method generates one entry
  44. * access for each mapping in the specified map, in the order that key-value
  45. * mappings are provided by the specified map's entry set iterator. <i>No
  46. * other methods generate entry accesses.</i> In particular, operations on
  47. * collection-views do <i>not</i> affect the order of iteration of the backing
  48. * map.
  49. *
  50. * <p>The {@link #removeEldestEntry(Map.Entry)} method may be overridden to
  51. * impose a policy for removing stale mappings automatically when new mappings
  52. * are added to the map.
  53. *
  54. * <p>This class provides all of the optional <tt>Map</tt> operations, and
  55. * permits null elements. Like <tt>HashMap</tt>, it provides constant-time
  56. * performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and
  57. * <tt>remove</tt>), assuming the the hash function disperses elements
  58. * properly among the buckets. Performance is likely to be just slightly
  59. * below that of <tt>HashMap</tt>, due to the added expense of maintaining the
  60. * linked list, with one exception: Iteration over the collection-views
  61. * of a <tt>LinkedHashMap</tt> requires time proportional to the <i>size</i>
  62. * of the map, regardless of its capacity. Iteration over a <tt>HashMap</tt>
  63. * is likely to be more expensive, requiring time proportional to its
  64. * <i>capacity</i>.
  65. *
  66. * <p>A linked hash map has two parameters that affect its performance:
  67. * <i>initial capacity</i> and <i>load factor</i>. They are defined precisely
  68. * as for <tt>HashMap</tt>. Note, however, that the penalty for choosing an
  69. * excessively high value for initial capacity is less severe for this class
  70. * than for <tt>HashMap</tt>, as iteration times for this class are unaffected
  71. * by capacity.
  72. *
  73. * <p><strong>Note that this implementation is not synchronized.</strong> If
  74. * multiple threads access a linked hash map concurrently, and at least
  75. * one of the threads modifies the map structurally, it <em>must</em> be
  76. * synchronized externally. This is typically accomplished by synchronizing
  77. * on some object that naturally encapsulates the map. If no such object
  78. * exists, the map should be "wrapped" using the
  79. * <tt>Collections.synchronizedMap</tt>method. This is best done at creation
  80. * time, to prevent accidental unsynchronized access:
  81. * <pre>
  82. * Map m = Collections.synchronizedMap(new LinkedHashMap(...));
  83. * </pre>
  84. * A structural modification is any operation that adds or deletes one or more
  85. * mappings or, in the case of access-ordered linked hash maps, affects
  86. * iteration order. In insertion-ordered linked hash maps, merely changing
  87. * the value associated with a key that is already contained in the map is not
  88. * a structural modification. <strong>In access-ordered linked hash maps,
  89. * merely querying the map with <tt>get</tt> is a structural
  90. * modification.</strong>)
  91. *
  92. * <p>The iterators returned by the <tt>iterator</tt> methods of the
  93. * collections returned by all of this class's collection view methods are
  94. * <em>fail-fast</em>: if the map is structurally modified at any time after
  95. * the iterator is created, in any way except through the iterator's own
  96. * remove method, the iterator will throw a
  97. * <tt>ConcurrentModificationException</tt>. Thus, in the face of concurrent
  98. * modification, the Iterator fails quickly and cleanly, rather than risking
  99. * arbitrary, non-deterministic behavior at an undetermined time in the
  100. * future.
  101. *
  102. * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  103. * as it is, generally speaking, impossible to make any hard guarantees in the
  104. * presence of unsynchronized concurrent modification. Fail-fast iterators
  105. * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
  106. * Therefore, it would be wrong to write a program that depended on this
  107. * exception for its correctness: <i>the fail-fast behavior of iterators
  108. * should be used only to detect bugs.</i>
  109. *
  110. * <p>This class is a member of the
  111. * <a href="{@docRoot}/../guide/collections/index.html">
  112. * Java Collections Framework</a>.
  113. *
  114. * @author Josh Bloch
  115. * @version 1.11, 01/23/03
  116. * @see Object#hashCode()
  117. * @see Collection
  118. * @see Map
  119. * @see HashMap
  120. * @see TreeMap
  121. * @see Hashtable
  122. * @since JDK1.4
  123. */
  124. public class LinkedHashMap extends HashMap {
  125. /**
  126. * The head of the doubly linked list.
  127. */
  128. private transient Entry header;
  129. /**
  130. * The iteration ordering method for this linked hash map: <tt>true</tt>
  131. * for access-order, <tt>false</tt> for insertion-order.
  132. *
  133. * @serial
  134. */
  135. private final boolean accessOrder;
  136. /**
  137. * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
  138. * with the specified initial capacity and load factor.
  139. *
  140. * @param initialCapacity the initial capacity.
  141. * @param loadFactor the load factor.
  142. * @throws IllegalArgumentException if the initial capacity is negative
  143. * or the load factor is nonpositive.
  144. */
  145. public LinkedHashMap(int initialCapacity, float loadFactor) {
  146. super(initialCapacity, loadFactor);
  147. accessOrder = false;
  148. }
  149. /**
  150. * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
  151. * with the specified initial capacity and a default load factor (0.75).
  152. *
  153. * @param initialCapacity the initial capacity.
  154. * @throws IllegalArgumentException if the initial capacity is negative.
  155. */
  156. public LinkedHashMap(int initialCapacity) {
  157. super(initialCapacity);
  158. accessOrder = false;
  159. }
  160. /**
  161. * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
  162. * with a default capacity (16) and load factor (0.75).
  163. */
  164. public LinkedHashMap() {
  165. super();
  166. accessOrder = false;
  167. }
  168. /**
  169. * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with
  170. * the same mappings as the specified map. The <tt>LinkedHashMap</tt>
  171. * instance is created with a a default load factor (0.75) and an initial
  172. * capacity sufficient to hold the mappings in the specified map.
  173. *
  174. * @param m the map whose mappings are to be placed in this map.
  175. * @throws NullPointerException if the specified map is null.
  176. */
  177. public LinkedHashMap(Map m) {
  178. super(m);
  179. accessOrder = false;
  180. }
  181. /**
  182. * Constructs an empty <tt>LinkedHashMap</tt> instance with the
  183. * specified initial capacity, load factor and ordering mode.
  184. *
  185. * @param initialCapacity the initial capacity.
  186. * @param loadFactor the load factor.
  187. * @param accessOrder the ordering mode - <tt>true</tt> for
  188. * access-order, <tt>false</tt> for insertion-order.
  189. * @throws IllegalArgumentException if the initial capacity is negative
  190. * or the load factor is nonpositive.
  191. */
  192. public LinkedHashMap(int initialCapacity, float loadFactor,
  193. boolean accessOrder) {
  194. super(initialCapacity, loadFactor);
  195. this.accessOrder = accessOrder;
  196. }
  197. /**
  198. * Called by superclass constructors and pseudoconstructors (clone,
  199. * readObject) before any entries are inserted into the map. Initializes
  200. * the chain.
  201. */
  202. void init() {
  203. header = new Entry(-1, null, null, null);
  204. header.before = header.after = header;
  205. }
  206. /**
  207. * Transfer all entries to new table array. This method is called
  208. * by superclass resize. It is overridden for performance, as it is
  209. * faster to iterate using our linked list.
  210. */
  211. void transfer(HashMap.Entry[] newTable) {
  212. int newCapacity = newTable.length;
  213. for (Entry e = header.after; e != header; e = e.after) {
  214. int index = indexFor(e.hash, newCapacity);
  215. e.next = newTable[index];
  216. newTable[index] = e;
  217. }
  218. }
  219. /**
  220. * Returns <tt>true</tt> if this map maps one or more keys to the
  221. * specified value.
  222. *
  223. * @param value value whose presence in this map is to be tested.
  224. * @return <tt>true</tt> if this map maps one or more keys to the
  225. * specified value.
  226. */
  227. public boolean containsValue(Object value) {
  228. // Overridden to take advantage of faster iterator
  229. if (value==null) {
  230. for (Entry e = header.after; e != header; e = e.after)
  231. if (e.value==null)
  232. return true;
  233. } else {
  234. for (Entry e = header.after; e != header; e = e.after)
  235. if (value.equals(e.value))
  236. return true;
  237. }
  238. return false;
  239. }
  240. /**
  241. * Returns the value to which this map maps the specified key. Returns
  242. * <tt>null</tt> if the map contains no mapping for this key. A return
  243. * value of <tt>null</tt> does not <i>necessarily</i> indicate that the
  244. * map contains no mapping for the key; it's also possible that the map
  245. * explicitly maps the key to <tt>null</tt>. The <tt>containsKey</tt>
  246. * operation may be used to distinguish these two cases.
  247. *
  248. * @return the value to which this map maps the specified key.
  249. * @param key key whose associated value is to be returned.
  250. */
  251. public Object get(Object key) {
  252. Entry e = (Entry)getEntry(key);
  253. if (e == null)
  254. return null;
  255. e.recordAccess(this);
  256. return e.value;
  257. }
  258. /**
  259. * Removes all mappings from this map.
  260. */
  261. public void clear() {
  262. super.clear();
  263. header.before = header.after = header;
  264. }
  265. /**
  266. * LinkedHashMap entry.
  267. */
  268. private static class Entry extends HashMap.Entry {
  269. // These fields comprise the doubly linked list used for iteration.
  270. Entry before, after;
  271. Entry(int hash, Object key, Object value, HashMap.Entry next) {
  272. super(hash, key, value, next);
  273. }
  274. /**
  275. * Remove this entry from the linked list.
  276. */
  277. private void remove() {
  278. before.after = after;
  279. after.before = before;
  280. }
  281. /**
  282. * Insert this entry before the specified existing entry in the list.
  283. */
  284. private void addBefore(Entry existingEntry) {
  285. after = existingEntry;
  286. before = existingEntry.before;
  287. before.after = this;
  288. after.before = this;
  289. }
  290. /**
  291. * This method is invoked by the superclass whenever the value
  292. * of a pre-existing entry is read by Map.get or modified by Map.set.
  293. * If the enclosing Map is access-ordered, it moves the entry
  294. * to the end of the list; otherwise, it does nothing.
  295. */
  296. void recordAccess(HashMap m) {
  297. LinkedHashMap lm = (LinkedHashMap)m;
  298. if (lm.accessOrder) {
  299. lm.modCount++;
  300. remove();
  301. addBefore(lm.header);
  302. }
  303. }
  304. void recordRemoval(HashMap m) {
  305. remove();
  306. }
  307. }
  308. private abstract class LinkedHashIterator implements Iterator {
  309. Entry nextEntry = header.after;
  310. Entry lastReturned = null;
  311. /**
  312. * The modCount value that the iterator believes that the backing
  313. * List should have. If this expectation is violated, the iterator
  314. * has detected concurrent modification.
  315. */
  316. int expectedModCount = modCount;
  317. public boolean hasNext() {
  318. return nextEntry != header;
  319. }
  320. public void remove() {
  321. if (lastReturned == null)
  322. throw new IllegalStateException();
  323. if (modCount != expectedModCount)
  324. throw new ConcurrentModificationException();
  325. LinkedHashMap.this.remove(lastReturned.key);
  326. lastReturned = null;
  327. expectedModCount = modCount;
  328. }
  329. Entry nextEntry() {
  330. if (modCount != expectedModCount)
  331. throw new ConcurrentModificationException();
  332. if (nextEntry == header)
  333. throw new NoSuchElementException();
  334. Entry e = lastReturned = nextEntry;
  335. nextEntry = e.after;
  336. return e;
  337. }
  338. }
  339. private class KeyIterator extends LinkedHashIterator {
  340. public Object next() { return nextEntry().getKey(); }
  341. }
  342. private class ValueIterator extends LinkedHashIterator {
  343. public Object next() { return nextEntry().value; }
  344. }
  345. private class EntryIterator extends LinkedHashIterator {
  346. public Object next() { return nextEntry(); }
  347. }
  348. // These Overrides alter the behavior of superclass view iterator() methods
  349. Iterator newKeyIterator() { return new KeyIterator(); }
  350. Iterator newValueIterator() { return new ValueIterator(); }
  351. Iterator newEntryIterator() { return new EntryIterator(); }
  352. /**
  353. * This override alters behavior of superclass put method. It causes newly
  354. * allocated entry to get inserted at the end of the linked list and
  355. * removes the eldest entry if appropriate.
  356. */
  357. void addEntry(int hash, Object key, Object value, int bucketIndex) {
  358. createEntry(hash, key, value, bucketIndex);
  359. // Remove eldest entry if instructed, else grow capacity if appropriate
  360. Entry eldest = header.after;
  361. if (removeEldestEntry(eldest)) {
  362. removeEntryForKey(eldest.key);
  363. } else {
  364. if (size >= threshold)
  365. resize(2 * table.length);
  366. }
  367. }
  368. /**
  369. * This override differs from addEntry in that it doesn't resize the
  370. * table or remove the eldest entry.
  371. */
  372. void createEntry(int hash, Object key, Object value, int bucketIndex) {
  373. Entry e = new Entry(hash, key, value, table[bucketIndex]);
  374. table[bucketIndex] = e;
  375. e.addBefore(header);
  376. size++;
  377. }
  378. /**
  379. * Returns <tt>true</tt> if this map should remove its eldest entry.
  380. * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
  381. * inserting a new entry into the map. It provides the implementer
  382. * with the opportunity to remove the eldest entry each time a new one
  383. * is added. This is useful if the map represents a cache: it allows
  384. * the map to reduce memory consumption by deleting stale entries.
  385. *
  386. * <p>Sample use: this override will allow the map to grow up to 100
  387. * entries and then delete the eldest entry each time a new entry is
  388. * added, maintaining a steady state of 100 entries.
  389. * <pre>
  390. * private static final int MAX_ENTRIES = 100;
  391. *
  392. * protected boolean removeEldestEntry(Map.Entry eldest) {
  393. * return size() > MAX_ENTRIES;
  394. * }
  395. * </pre>
  396. *
  397. * <p>This method typically does not modify the map in any way,
  398. * instead allowing the map to modify itself as directed by its
  399. * return value. It <i>is</i> permitted for this method to modify
  400. * the map directly, but if it does so, it <i>must</i> return
  401. * <tt>false</tt> (indicating that the map should not attempt any
  402. * further modification). The effects of returning <tt>true</tt>
  403. * after modifying the map from within this method are unspecified.
  404. *
  405. * <p>This implementation merely returns <tt>false</tt> (so that this
  406. * map acts like a normal map - the eldest element is never removed).
  407. *
  408. * @param eldest The least recently inserted entry in the map, or if
  409. * this is an access-ordered map, the least recently accessed
  410. * entry. This is the entry that will be removed it this
  411. * method returns <tt>true</tt>. If the map was empty prior
  412. * to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
  413. * in this invocation, this will be the entry that was just
  414. * inserted; in other words, if the map contains a single
  415. * entry, the eldest entry is also the newest.
  416. * @return <tt>true</tt> if the eldest entry should be removed
  417. * from the map; <tt>false</t> if it should be retained.
  418. */
  419. protected boolean removeEldestEntry(Map.Entry eldest) {
  420. return false;
  421. }
  422. }