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. 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 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.18, 02/19/04
  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<K,V>
  125. extends HashMap<K,V>
  126. implements Map<K,V>
  127. {
  128. private static final long serialVersionUID = 3801124242820219131L;
  129. /**
  130. * The head of the doubly linked list.
  131. */
  132. private transient Entry<K,V> header;
  133. /**
  134. * The iteration ordering method for this linked hash map: <tt>true</tt>
  135. * for access-order, <tt>false</tt> for insertion-order.
  136. *
  137. * @serial
  138. */
  139. private final boolean accessOrder;
  140. /**
  141. * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
  142. * with the specified initial capacity and load factor.
  143. *
  144. * @param initialCapacity the initial capacity.
  145. * @param loadFactor the load factor.
  146. * @throws IllegalArgumentException if the initial capacity is negative
  147. * or the load factor is nonpositive.
  148. */
  149. public LinkedHashMap(int initialCapacity, float loadFactor) {
  150. super(initialCapacity, loadFactor);
  151. accessOrder = false;
  152. }
  153. /**
  154. * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
  155. * with the specified initial capacity and a default load factor (0.75).
  156. *
  157. * @param initialCapacity the initial capacity.
  158. * @throws IllegalArgumentException if the initial capacity is negative.
  159. */
  160. public LinkedHashMap(int initialCapacity) {
  161. super(initialCapacity);
  162. accessOrder = false;
  163. }
  164. /**
  165. * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
  166. * with a default capacity (16) and load factor (0.75).
  167. */
  168. public LinkedHashMap() {
  169. super();
  170. accessOrder = false;
  171. }
  172. /**
  173. * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with
  174. * the same mappings as the specified map. The <tt>LinkedHashMap</tt>
  175. * instance is created with a a default load factor (0.75) and an initial
  176. * capacity sufficient to hold the mappings in the specified map.
  177. *
  178. * @param m the map whose mappings are to be placed in this map.
  179. * @throws NullPointerException if the specified map is null.
  180. */
  181. public LinkedHashMap(Map<? extends K, ? extends V> m) {
  182. super(m);
  183. accessOrder = false;
  184. }
  185. /**
  186. * Constructs an empty <tt>LinkedHashMap</tt> instance with the
  187. * specified initial capacity, load factor and ordering mode.
  188. *
  189. * @param initialCapacity the initial capacity.
  190. * @param loadFactor the load factor.
  191. * @param accessOrder the ordering mode - <tt>true</tt> for
  192. * access-order, <tt>false</tt> for insertion-order.
  193. * @throws IllegalArgumentException if the initial capacity is negative
  194. * or the load factor is nonpositive.
  195. */
  196. public LinkedHashMap(int initialCapacity,
  197. float loadFactor,
  198. boolean accessOrder) {
  199. super(initialCapacity, loadFactor);
  200. this.accessOrder = accessOrder;
  201. }
  202. /**
  203. * Called by superclass constructors and pseudoconstructors (clone,
  204. * readObject) before any entries are inserted into the map. Initializes
  205. * the chain.
  206. */
  207. void init() {
  208. header = new Entry<K,V>(-1, null, null, null);
  209. header.before = header.after = header;
  210. }
  211. /**
  212. * Transfer all entries to new table array. This method is called
  213. * by superclass resize. It is overridden for performance, as it is
  214. * faster to iterate using our linked list.
  215. */
  216. void transfer(HashMap.Entry[] newTable) {
  217. int newCapacity = newTable.length;
  218. for (Entry<K,V> e = header.after; e != header; e = e.after) {
  219. int index = indexFor(e.hash, newCapacity);
  220. e.next = newTable[index];
  221. newTable[index] = e;
  222. }
  223. }
  224. /**
  225. * Returns <tt>true</tt> if this map maps one or more keys to the
  226. * specified value.
  227. *
  228. * @param value value whose presence in this map is to be tested.
  229. * @return <tt>true</tt> if this map maps one or more keys to the
  230. * specified value.
  231. */
  232. public boolean containsValue(Object value) {
  233. // Overridden to take advantage of faster iterator
  234. if (value==null) {
  235. for (Entry e = header.after; e != header; e = e.after)
  236. if (e.value==null)
  237. return true;
  238. } else {
  239. for (Entry e = header.after; e != header; e = e.after)
  240. if (value.equals(e.value))
  241. return true;
  242. }
  243. return false;
  244. }
  245. /**
  246. * Returns the value to which this map maps the specified key. Returns
  247. * <tt>null</tt> if the map contains no mapping for this key. A return
  248. * value of <tt>null</tt> does not <i>necessarily</i> indicate that the
  249. * map contains no mapping for the key; it's also possible that the map
  250. * explicitly maps the key to <tt>null</tt>. The <tt>containsKey</tt>
  251. * operation may be used to distinguish these two cases.
  252. *
  253. * @return the value to which this map maps the specified key.
  254. * @param key key whose associated value is to be returned.
  255. */
  256. public V get(Object key) {
  257. Entry<K,V> e = (Entry<K,V>)getEntry(key);
  258. if (e == null)
  259. return null;
  260. e.recordAccess(this);
  261. return e.value;
  262. }
  263. /**
  264. * Removes all mappings from this map.
  265. */
  266. public void clear() {
  267. super.clear();
  268. header.before = header.after = header;
  269. }
  270. /**
  271. * LinkedHashMap entry.
  272. */
  273. private static class Entry<K,V> extends HashMap.Entry<K,V> {
  274. // These fields comprise the doubly linked list used for iteration.
  275. Entry<K,V> before, after;
  276. Entry(int hash, K key, V value, HashMap.Entry<K,V> next) {
  277. super(hash, key, value, next);
  278. }
  279. /**
  280. * Remove this entry from the linked list.
  281. */
  282. private void remove() {
  283. before.after = after;
  284. after.before = before;
  285. }
  286. /**
  287. * Insert this entry before the specified existing entry in the list.
  288. */
  289. private void addBefore(Entry<K,V> existingEntry) {
  290. after = existingEntry;
  291. before = existingEntry.before;
  292. before.after = this;
  293. after.before = this;
  294. }
  295. /**
  296. * This method is invoked by the superclass whenever the value
  297. * of a pre-existing entry is read by Map.get or modified by Map.set.
  298. * If the enclosing Map is access-ordered, it moves the entry
  299. * to the end of the list; otherwise, it does nothing.
  300. */
  301. void recordAccess(HashMap<K,V> m) {
  302. LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
  303. if (lm.accessOrder) {
  304. lm.modCount++;
  305. remove();
  306. addBefore(lm.header);
  307. }
  308. }
  309. void recordRemoval(HashMap<K,V> m) {
  310. remove();
  311. }
  312. }
  313. private abstract class LinkedHashIterator<T> implements Iterator<T> {
  314. Entry<K,V> nextEntry = header.after;
  315. Entry<K,V> lastReturned = null;
  316. /**
  317. * The modCount value that the iterator believes that the backing
  318. * List should have. If this expectation is violated, the iterator
  319. * has detected concurrent modification.
  320. */
  321. int expectedModCount = modCount;
  322. public boolean hasNext() {
  323. return nextEntry != header;
  324. }
  325. public void remove() {
  326. if (lastReturned == null)
  327. throw new IllegalStateException();
  328. if (modCount != expectedModCount)
  329. throw new ConcurrentModificationException();
  330. LinkedHashMap.this.remove(lastReturned.key);
  331. lastReturned = null;
  332. expectedModCount = modCount;
  333. }
  334. Entry<K,V> nextEntry() {
  335. if (modCount != expectedModCount)
  336. throw new ConcurrentModificationException();
  337. if (nextEntry == header)
  338. throw new NoSuchElementException();
  339. Entry<K,V> e = lastReturned = nextEntry;
  340. nextEntry = e.after;
  341. return e;
  342. }
  343. }
  344. private class KeyIterator extends LinkedHashIterator<K> {
  345. public K next() { return nextEntry().getKey(); }
  346. }
  347. private class ValueIterator extends LinkedHashIterator<V> {
  348. public V next() { return nextEntry().value; }
  349. }
  350. private class EntryIterator extends LinkedHashIterator<Map.Entry<K,V>> {
  351. public Map.Entry<K,V> next() { return nextEntry(); }
  352. }
  353. // These Overrides alter the behavior of superclass view iterator() methods
  354. Iterator<K> newKeyIterator() { return new KeyIterator(); }
  355. Iterator<V> newValueIterator() { return new ValueIterator(); }
  356. Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); }
  357. /**
  358. * This override alters behavior of superclass put method. It causes newly
  359. * allocated entry to get inserted at the end of the linked list and
  360. * removes the eldest entry if appropriate.
  361. */
  362. void addEntry(int hash, K key, V value, int bucketIndex) {
  363. createEntry(hash, key, value, bucketIndex);
  364. // Remove eldest entry if instructed, else grow capacity if appropriate
  365. Entry<K,V> eldest = header.after;
  366. if (removeEldestEntry(eldest)) {
  367. removeEntryForKey(eldest.key);
  368. } else {
  369. if (size >= threshold)
  370. resize(2 * table.length);
  371. }
  372. }
  373. /**
  374. * This override differs from addEntry in that it doesn't resize the
  375. * table or remove the eldest entry.
  376. */
  377. void createEntry(int hash, K key, V value, int bucketIndex) {
  378. HashMap.Entry<K,V> old = table[bucketIndex];
  379. Entry<K,V> e = new Entry<K,V>(hash, key, value, old);
  380. table[bucketIndex] = e;
  381. e.addBefore(header);
  382. size++;
  383. }
  384. /**
  385. * Returns <tt>true</tt> if this map should remove its eldest entry.
  386. * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
  387. * inserting a new entry into the map. It provides the implementer
  388. * with the opportunity to remove the eldest entry each time a new one
  389. * is added. This is useful if the map represents a cache: it allows
  390. * the map to reduce memory consumption by deleting stale entries.
  391. *
  392. * <p>Sample use: this override will allow the map to grow up to 100
  393. * entries and then delete the eldest entry each time a new entry is
  394. * added, maintaining a steady state of 100 entries.
  395. * <pre>
  396. * private static final int MAX_ENTRIES = 100;
  397. *
  398. * protected boolean removeEldestEntry(Map.Entry eldest) {
  399. * return size() > MAX_ENTRIES;
  400. * }
  401. * </pre>
  402. *
  403. * <p>This method typically does not modify the map in any way,
  404. * instead allowing the map to modify itself as directed by its
  405. * return value. It <i>is</i> permitted for this method to modify
  406. * the map directly, but if it does so, it <i>must</i> return
  407. * <tt>false</tt> (indicating that the map should not attempt any
  408. * further modification). The effects of returning <tt>true</tt>
  409. * after modifying the map from within this method are unspecified.
  410. *
  411. * <p>This implementation merely returns <tt>false</tt> (so that this
  412. * map acts like a normal map - the eldest element is never removed).
  413. *
  414. * @param eldest The least recently inserted entry in the map, or if
  415. * this is an access-ordered map, the least recently accessed
  416. * entry. This is the entry that will be removed it this
  417. * method returns <tt>true</tt>. If the map was empty prior
  418. * to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
  419. * in this invocation, this will be the entry that was just
  420. * inserted; in other words, if the map contains a single
  421. * entry, the eldest entry is also the newest.
  422. * @return <tt>true</tt> if the eldest entry should be removed
  423. * from the map; <tt>false</t> if it should be retained.
  424. */
  425. protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
  426. return false;
  427. }
  428. }