1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27 package java.util; 28 29 import sun.misc.Hashing; 30 31 import java.io.*; 32 import java.util.function.BiFunction; 33 import java.util.function.Consumer; 34 import java.util.function.BiConsumer; 35 36 /** 37 * <p>Hash table and linked list implementation of the <tt>Map</tt> interface, 38 * with predictable iteration order. This implementation differs from 39 * <tt>HashMap</tt> in that it maintains a doubly-linked list running through 40 * all of its entries. This linked list defines the iteration ordering, 41 * which is normally the order in which keys were inserted into the map 42 * (<i>insertion-order</i>). Note that insertion order is not affected 43 * if a key is <i>re-inserted</i> into the map. (A key <tt>k</tt> is 44 * reinserted into a map <tt>m</tt> if <tt>m.put(k, v)</tt> is invoked when 45 * <tt>m.containsKey(k)</tt> would return <tt>true</tt> immediately prior to 46 * the invocation.) 47 * 48 * <p>This implementation spares its clients from the unspecified, generally 49 * chaotic ordering provided by {@link HashMap} (and {@link Hashtable}), 50 * without incurring the increased cost associated with {@link TreeMap}. It 51 * can be used to produce a copy of a map that has the same order as the 52 * original, regardless of the original map's implementation: 53 * <pre> 54 * void foo(Map m) { 55 * Map copy = new LinkedHashMap(m); 56 * ... 57 * } 58 * </pre> 59 * This technique is particularly useful if a module takes a map on input, 60 * copies it, and later returns results whose order is determined by that of 61 * the copy. (Clients generally appreciate having things returned in the same 62 * order they were presented.) 63 * 64 * <p>A special {@link #LinkedHashMap(int,float,boolean) constructor} is 65 * provided to create a linked hash map whose order of iteration is the order 66 * in which its entries were last accessed, from least-recently accessed to 67 * most-recently (<i>access-order</i>). This kind of map is well-suited to 68 * building LRU caches. Invoking the {@code put}, {@code putIfAbsent}, 69 * {@code get}, {@code getOrDefault}, {@code compute}, {@code computeIfAbsent}, 70 * {@code computeIfPresent}, or {@code merge} methods results 71 * in an access to the corresponding entry (assuming it exists after the 72 * invocation completes). The {@code replace} methods only result in an access 73 * of the entry if the value is replaced. The {@code putAll} method generates one 74 * entry access for each mapping in the specified map, in the order that 75 * key-value mappings are provided by the specified map's entry set iterator. 76 * <i>No other methods generate entry accesses.</i> In particular, operations 77 * on collection-views do <i>not</i> affect the order of iteration of the 78 * backing map. * 79 * <p>The {@link #removeEldestEntry(Map.Entry)} method may be overridden to 80 * impose a policy for removing stale mappings automatically when new mappings 81 * are added to the map. 82 * 83 * <p>This class provides all of the optional <tt>Map</tt> operations, and 84 * permits null elements. Like <tt>HashMap</tt>, it provides constant-time 85 * performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and 86 * <tt>remove</tt>), assuming the hash function disperses elements 87 * properly among the buckets. Performance is likely to be just slightly 88 * below that of <tt>HashMap</tt>, due to the added expense of maintaining the 89 * linked list, with one exception: Iteration over the collection-views 90 * of a <tt>LinkedHashMap</tt> requires time proportional to the <i>size</i> 91 * of the map, regardless of its capacity. Iteration over a <tt>HashMap</tt> 92 * is likely to be more expensive, requiring time proportional to its 93 * <i>capacity</i>. 94 * 95 * <p>A linked hash map has two parameters that affect its performance: 96 * <i>initial capacity</i> and <i>load factor</i>. They are defined precisely 97 * as for <tt>HashMap</tt>. Note, however, that the penalty for choosing an 98 * excessively high value for initial capacity is less severe for this class 99 * than for <tt>HashMap</tt>, as iteration times for this class are unaffected 100 * by capacity. 101 * 102 * <p><strong>Note that this implementation is not synchronized.</strong> 103 * If multiple threads access a linked hash map concurrently, and at least 104 * one of the threads modifies the map structurally, it <em>must</em> be 105 * synchronized externally. This is typically accomplished by 106 * synchronizing on some object that naturally encapsulates the map. 107 * 108 * If no such object exists, the map should be "wrapped" using the 109 * {@link Collections#synchronizedMap Collections.synchronizedMap} 110 * method. This is best done at creation time, to prevent accidental 111 * unsynchronized access to the map:<pre> 112 * Map m = Collections.synchronizedMap(new LinkedHashMap(...));</pre> 113 * 114 * A structural modification is any operation that adds or deletes one or more 115 * mappings or, in the case of access-ordered linked hash maps, affects 116 * iteration order. In insertion-ordered linked hash maps, merely changing 117 * the value associated with a key that is already contained in the map is not 118 * a structural modification. <strong>In access-ordered linked hash maps, 119 * merely querying the map with <tt>get</tt> is a structural 120 * modification.</strong>) 121 * 122 * <p>The iterators returned by the <tt>iterator</tt> method of the collections 123 * returned by all of this class's collection view methods are 124 * <em>fail-fast</em>: if the map is structurally modified at any time after 125 * the iterator is created, in any way except through the iterator's own 126 * <tt>remove</tt> method, the iterator will throw a {@link 127 * ConcurrentModificationException}. Thus, in the face of concurrent 128 * modification, the iterator fails quickly and cleanly, rather than risking 129 * arbitrary, non-deterministic behavior at an undetermined time in the future. 130 * 131 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed 132 * as it is, generally speaking, impossible to make any hard guarantees in the 133 * presence of unsynchronized concurrent modification. Fail-fast iterators 134 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. 135 * Therefore, it would be wrong to write a program that depended on this 136 * exception for its correctness: <i>the fail-fast behavior of iterators 137 * should be used only to detect bugs.</i> 138 * 139 * <p>The spliterators returned by the spliterator method of the collections 140 * returned by all of this class's collection view methods are 141 * <em><a href="Spliterator.html#binding">late-binding</a></em>, 142 * <em>fail-fast</em>, and additionally report {@link Spliterator#ORDERED}. 143 * 144 * <p>This class is a member of the 145 * <a href="{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/collections/index.html"> 146 * Java Collections Framework</a>. 147 * 148 * @implNote 149 * The spliterators returned by the spliterator method of the collections 150 * returned by all of this class's collection view methods are created from 151 * the iterators of the corresponding collections. 152 * 153 * @param <K> the type of keys maintained by this map 154 * @param <V> the type of mapped values 155 * 156 * @author Josh Bloch 157 * @see Object#hashCode() 158 * @see Collection 159 * @see Map 160 * @see HashMap 161 * @see TreeMap 162 * @see Hashtable 163 * @since 1.4 164 */ 165 166 public class LinkedHashMap<K,V> 167 extends HashMap<K,V> 168 implements Map<K,V> 169 { 170 171 private static final long serialVersionUID = 3801124242820219131L; 172 173 /** 174 * The head of the doubly linked list. 175 */ 176 private transient LinkedHashMapEntry<K,V> header; 177 178 /** 179 * The iteration ordering method for this linked hash map: <tt>true</tt> 180 * for access-order, <tt>false</tt> for insertion-order. 181 * 182 * @serial 183 */ 184 private final boolean accessOrder; 185 186 /** 187 * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance 188 * with the specified initial capacity and load factor. 189 * 190 * @param initialCapacity the initial capacity 191 * @param loadFactor the load factor 192 * @throws IllegalArgumentException if the initial capacity is negative 193 * or the load factor is nonpositive 194 */ LinkedHashMap(int initialCapacity, float loadFactor)195 public LinkedHashMap(int initialCapacity, float loadFactor) { 196 super(initialCapacity, loadFactor); 197 accessOrder = false; 198 } 199 200 /** 201 * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance 202 * with the specified initial capacity and a default load factor (0.75). 203 * 204 * @param initialCapacity the initial capacity 205 * @throws IllegalArgumentException if the initial capacity is negative 206 */ LinkedHashMap(int initialCapacity)207 public LinkedHashMap(int initialCapacity) { 208 super(initialCapacity); 209 accessOrder = false; 210 } 211 212 /** 213 * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance 214 * with the default initial capacity (16) and load factor (0.75). 215 */ LinkedHashMap()216 public LinkedHashMap() { 217 super(); 218 accessOrder = false; 219 } 220 221 /** 222 * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with 223 * the same mappings as the specified map. The <tt>LinkedHashMap</tt> 224 * instance is created with a default load factor (0.75) and an initial 225 * capacity sufficient to hold the mappings in the specified map. 226 * 227 * @param m the map whose mappings are to be placed in this map 228 * @throws NullPointerException if the specified map is null 229 */ LinkedHashMap(Map<? extends K, ? extends V> m)230 public LinkedHashMap(Map<? extends K, ? extends V> m) { 231 super(m); 232 accessOrder = false; 233 } 234 235 /** 236 * Constructs an empty <tt>LinkedHashMap</tt> instance with the 237 * specified initial capacity, load factor and ordering mode. 238 * 239 * @param initialCapacity the initial capacity 240 * @param loadFactor the load factor 241 * @param accessOrder the ordering mode - <tt>true</tt> for 242 * access-order, <tt>false</tt> for insertion-order 243 * @throws IllegalArgumentException if the initial capacity is negative 244 * or the load factor is nonpositive 245 */ LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)246 public LinkedHashMap(int initialCapacity, 247 float loadFactor, 248 boolean accessOrder) { 249 super(initialCapacity, loadFactor); 250 this.accessOrder = accessOrder; 251 } 252 253 /** 254 * Called by superclass constructors and pseudoconstructors (clone, 255 * readObject) before any entries are inserted into the map. Initializes 256 * the chain. 257 */ 258 @Override init()259 void init() { 260 header = new LinkedHashMapEntry<>(-1, null, null, null); 261 header.before = header.after = header; 262 } 263 264 /** 265 * Transfers all entries to new table array. This method is called 266 * by superclass resize. It is overridden for performance, as it is 267 * faster to iterate using our linked list. 268 */ 269 @Override transfer(HashMapEntry[] newTable)270 void transfer(HashMapEntry[] newTable) { 271 int newCapacity = newTable.length; 272 for (LinkedHashMapEntry<K,V> e = header.after; e != header; e = e.after) { 273 int index = indexFor(e.hash, newCapacity); 274 e.next = newTable[index]; 275 newTable[index] = e; 276 } 277 } 278 279 280 /** 281 * Returns <tt>true</tt> if this map maps one or more keys to the 282 * specified value. 283 * 284 * @param value value whose presence in this map is to be tested 285 * @return <tt>true</tt> if this map maps one or more keys to the 286 * specified value 287 */ containsValue(Object value)288 public boolean containsValue(Object value) { 289 // Overridden to take advantage of faster iterator 290 if (value==null) { 291 for (LinkedHashMapEntry e = header.after; e != header; e = e.after) 292 if (e.value==null) 293 return true; 294 } else { 295 for (LinkedHashMapEntry e = header.after; e != header; e = e.after) 296 if (value.equals(e.value)) 297 return true; 298 } 299 return false; 300 } 301 302 /** 303 * Returns the value to which the specified key is mapped, 304 * or {@code null} if this map contains no mapping for the key. 305 * 306 * <p>More formally, if this map contains a mapping from a key 307 * {@code k} to a value {@code v} such that {@code (key==null ? k==null : 308 * key.equals(k))}, then this method returns {@code v}; otherwise 309 * it returns {@code null}. (There can be at most one such mapping.) 310 * 311 * <p>A return value of {@code null} does not <i>necessarily</i> 312 * indicate that the map contains no mapping for the key; it's also 313 * possible that the map explicitly maps the key to {@code null}. 314 * The {@link #containsKey containsKey} operation may be used to 315 * distinguish these two cases. 316 */ get(Object key)317 public V get(Object key) { 318 LinkedHashMapEntry<K,V> e = (LinkedHashMapEntry<K,V>)getEntry(key); 319 if (e == null) 320 return null; 321 e.recordAccess(this); 322 return e.value; 323 } 324 325 /** 326 * Removes all of the mappings from this map. 327 * The map will be empty after this call returns. 328 */ clear()329 public void clear() { 330 super.clear(); 331 header.before = header.after = header; 332 } 333 334 /** 335 * LinkedHashMap entry. 336 */ 337 private static class LinkedHashMapEntry<K,V> extends HashMapEntry<K,V> { 338 // These fields comprise the doubly linked list used for iteration. 339 LinkedHashMapEntry<K,V> before, after; 340 LinkedHashMapEntry(int hash, K key, V value, HashMapEntry<K,V> next)341 LinkedHashMapEntry(int hash, K key, V value, HashMapEntry<K,V> next) { 342 super(hash, key, value, next); 343 } 344 345 /** 346 * Removes this entry from the linked list. 347 */ remove()348 private void remove() { 349 before.after = after; 350 after.before = before; 351 } 352 353 /** 354 * Inserts this entry before the specified existing entry in the list. 355 */ addBefore(LinkedHashMapEntry<K,V> existingEntry)356 private void addBefore(LinkedHashMapEntry<K,V> existingEntry) { 357 after = existingEntry; 358 before = existingEntry.before; 359 before.after = this; 360 after.before = this; 361 } 362 363 /** 364 * This method is invoked by the superclass whenever the value 365 * of a pre-existing entry is read by Map.get or modified by Map.set. 366 * If the enclosing Map is access-ordered, it moves the entry 367 * to the end of the list; otherwise, it does nothing. 368 */ recordAccess(HashMap<K,V> m)369 void recordAccess(HashMap<K,V> m) { 370 LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m; 371 if (lm.accessOrder) { 372 lm.modCount++; 373 remove(); 374 addBefore(lm.header); 375 } 376 } 377 recordRemoval(HashMap<K,V> m)378 void recordRemoval(HashMap<K,V> m) { 379 remove(); 380 } 381 } 382 383 private abstract class LinkedHashIterator<T> implements Iterator<T> { 384 LinkedHashMapEntry<K,V> nextEntry = header.after; 385 LinkedHashMapEntry<K,V> lastReturned = null; 386 387 /** 388 * The modCount value that the iterator believes that the backing 389 * List should have. If this expectation is violated, the iterator 390 * has detected concurrent modification. 391 */ 392 int expectedModCount = modCount; 393 hasNext()394 public boolean hasNext() { 395 return nextEntry != header; 396 } 397 remove()398 public void remove() { 399 if (lastReturned == null) 400 throw new IllegalStateException(); 401 if (modCount != expectedModCount) 402 throw new ConcurrentModificationException(); 403 404 LinkedHashMap.this.remove(lastReturned.key); 405 lastReturned = null; 406 expectedModCount = modCount; 407 } 408 nextEntry()409 Entry<K,V> nextEntry() { 410 if (modCount != expectedModCount) 411 throw new ConcurrentModificationException(); 412 if (nextEntry == header) 413 throw new NoSuchElementException(); 414 415 LinkedHashMapEntry<K,V> e = lastReturned = nextEntry; 416 nextEntry = e.after; 417 return e; 418 } 419 } 420 421 private class KeyIterator extends LinkedHashIterator<K> { next()422 public K next() { return nextEntry().getKey(); } 423 } 424 425 private class ValueIterator extends LinkedHashIterator<V> { next()426 public V next() { return nextEntry().getValue(); } 427 } 428 429 private class EntryIterator extends LinkedHashIterator<Map.Entry<K,V>> { next()430 public Map.Entry<K,V> next() { return nextEntry(); } 431 } 432 433 // These Overrides alter the behavior of superclass view iterator() methods newKeyIterator()434 Iterator<K> newKeyIterator() { return new KeyIterator(); } newValueIterator()435 Iterator<V> newValueIterator() { return new ValueIterator(); } newEntryIterator()436 Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); } 437 438 /** 439 * This override alters behavior of superclass put method. It causes newly 440 * allocated entry to get inserted at the end of the linked list and 441 * removes the eldest entry if appropriate. 442 */ addEntry(int hash, K key, V value, int bucketIndex)443 void addEntry(int hash, K key, V value, int bucketIndex) { 444 // Previous Android releases called removeEldestEntry() before actually 445 // inserting a value but after increasing the size. 446 // The RI is documented to call it afterwards. 447 // **** THIS CHANGE WILL BE REVERTED IN A FUTURE ANDROID RELEASE **** 448 449 // Remove eldest entry if instructed 450 LinkedHashMapEntry<K,V> eldest = header.after; 451 if (eldest != header) { 452 boolean removeEldest; 453 size++; 454 try { 455 removeEldest = removeEldestEntry(eldest); 456 } finally { 457 size--; 458 } 459 if (removeEldest) { 460 removeEntryForKey(eldest.key); 461 } 462 } 463 464 super.addEntry(hash, key, value, bucketIndex); 465 } 466 467 /** 468 * Returns the eldest entry in the map, or {@code null} if the map is empty. 469 * 470 * Android-added. 471 * 472 * @hide 473 */ eldest()474 public Map.Entry<K, V> eldest() { 475 Entry<K, V> eldest = header.after; 476 return eldest != header ? eldest : null; 477 } 478 479 /** 480 * This override differs from addEntry in that it doesn't resize the 481 * table or remove the eldest entry. 482 */ createEntry(int hash, K key, V value, int bucketIndex)483 void createEntry(int hash, K key, V value, int bucketIndex) { 484 HashMapEntry<K,V> old = table[bucketIndex]; 485 LinkedHashMapEntry<K,V> e = new LinkedHashMapEntry<>(hash, key, value, old); 486 table[bucketIndex] = e; 487 e.addBefore(header); 488 size++; 489 } 490 491 // Intentionally make this not JavaDoc, as the we don't conform to 492 // the behaviour documented here (we call removeEldestEntry before 493 // inserting the new value to be consistent with previous Android 494 // releases). 495 // **** THIS CHANGE WILL BE REVERTED IN A FUTURE ANDROID RELEASE **** 496 /* 497 * Returns <tt>true</tt> if this map should remove its eldest entry. 498 * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after 499 * inserting a new entry into the map. It provides the implementor 500 * with the opportunity to remove the eldest entry each time a new one 501 * is added. This is useful if the map represents a cache: it allows 502 * the map to reduce memory consumption by deleting stale entries. 503 * 504 * <p>Sample use: this override will allow the map to grow up to 100 505 * entries and then delete the eldest entry each time a new entry is 506 * added, maintaining a steady state of 100 entries. 507 * <pre> 508 * private static final int MAX_ENTRIES = 100; 509 * 510 * protected boolean removeEldestEntry(Map.Entry eldest) { 511 * return size() > MAX_ENTRIES; 512 * } 513 * </pre> 514 * 515 * <p>This method typically does not modify the map in any way, 516 * instead allowing the map to modify itself as directed by its 517 * return value. It <i>is</i> permitted for this method to modify 518 * the map directly, but if it does so, it <i>must</i> return 519 * <tt>false</tt> (indicating that the map should not attempt any 520 * further modification). The effects of returning <tt>true</tt> 521 * after modifying the map from within this method are unspecified. 522 * 523 * <p>This implementation merely returns <tt>false</tt> (so that this 524 * map acts like a normal map - the eldest element is never removed). 525 * 526 * @param eldest The least recently inserted entry in the map, or if 527 * this is an access-ordered map, the least recently accessed 528 * entry. This is the entry that will be removed it this 529 * method returns <tt>true</tt>. If the map was empty prior 530 * to the <tt>put</tt> or <tt>putAll</tt> invocation resulting 531 * in this invocation, this will be the entry that was just 532 * inserted; in other words, if the map contains a single 533 * entry, the eldest entry is also the newest. 534 * @return <tt>true</tt> if the eldest entry should be removed 535 * from the map; <tt>false</tt> if it should be retained. 536 */ removeEldestEntry(Map.Entry<K,V> eldest)537 protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { 538 return false; 539 } 540 541 // Map overrides forEach(BiConsumer<? super K, ? super V> action)542 public void forEach(BiConsumer<? super K, ? super V> action) { 543 if (action == null) 544 throw new NullPointerException(); 545 int mc = modCount; 546 // Android modified - breaks from the loop when modCount != mc 547 for (LinkedHashMapEntry<K,V> e = header.after; modCount == mc && e != header; e = e.after) 548 action.accept(e.key, e.value); 549 if (modCount != mc) 550 throw new ConcurrentModificationException(); 551 } 552 replaceAll(BiFunction<? super K, ? super V, ? extends V> function)553 public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { 554 if (function == null) 555 throw new NullPointerException(); 556 int mc = modCount; 557 // Android modified - breaks from the loop when modCount != mc 558 for (LinkedHashMapEntry<K,V> e = header.after; modCount == mc && e != header; e = e.after) 559 e.value = function.apply(e.key, e.value); 560 if (modCount != mc) 561 throw new ConcurrentModificationException(); 562 } 563 } 564