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