1 /* 2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.util; 27 28 import java.util.function.Consumer; 29 import java.util.function.BiConsumer; 30 import java.util.function.BiFunction; 31 import java.io.IOException; 32 33 // Android-added: Note about spliterator order b/33945212 in Android N 34 /** 35 * <p>Hash table and linked list implementation of the <tt>Map</tt> interface, 36 * with predictable iteration order. This implementation differs from 37 * <tt>HashMap</tt> in that it maintains a doubly-linked list running through 38 * all of its entries. This linked list defines the iteration ordering, 39 * which is normally the order in which keys were inserted into the map 40 * (<i>insertion-order</i>). Note that insertion order is not affected 41 * if a key is <i>re-inserted</i> into the map. (A key <tt>k</tt> is 42 * reinserted into a map <tt>m</tt> if <tt>m.put(k, v)</tt> is invoked when 43 * <tt>m.containsKey(k)</tt> would return <tt>true</tt> immediately prior to 44 * the invocation.) 45 * 46 * <p>This implementation spares its clients from the unspecified, generally 47 * chaotic ordering provided by {@link HashMap} (and {@link Hashtable}), 48 * without incurring the increased cost associated with {@link TreeMap}. It 49 * can be used to produce a copy of a map that has the same order as the 50 * original, regardless of the original map's implementation: 51 * <pre> 52 * void foo(Map m) { 53 * Map copy = new LinkedHashMap(m); 54 * ... 55 * } 56 * </pre> 57 * This technique is particularly useful if a module takes a map on input, 58 * copies it, and later returns results whose order is determined by that of 59 * the copy. (Clients generally appreciate having things returned in the same 60 * order they were presented.) 61 * 62 * <p>A special {@link #LinkedHashMap(int,float,boolean) constructor} is 63 * provided to create a linked hash map whose order of iteration is the order 64 * in which its entries were last accessed, from least-recently accessed to 65 * most-recently (<i>access-order</i>). This kind of map is well-suited to 66 * building LRU caches. Invoking the {@code put}, {@code putIfAbsent}, 67 * {@code get}, {@code getOrDefault}, {@code compute}, {@code computeIfAbsent}, 68 * {@code computeIfPresent}, or {@code merge} methods results 69 * in an access to the corresponding entry (assuming it exists after the 70 * invocation completes). The {@code replace} methods only result in an access 71 * of the entry if the value is replaced. The {@code putAll} method generates one 72 * entry access for each mapping in the specified map, in the order that 73 * key-value mappings are provided by the specified map's entry set iterator. 74 * <i>No other methods generate entry accesses.</i> In particular, operations 75 * on collection-views do <i>not</i> affect the order of iteration of the 76 * backing map. 77 * 78 * <p>The {@link #removeEldestEntry(Map.Entry)} method may be overridden to 79 * impose a policy for removing stale mappings automatically when new mappings 80 * are added to the map. 81 * 82 * <p>This class provides all of the optional <tt>Map</tt> operations, and 83 * permits null elements. Like <tt>HashMap</tt>, it provides constant-time 84 * performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and 85 * <tt>remove</tt>), assuming the hash function disperses elements 86 * properly among the buckets. Performance is likely to be just slightly 87 * below that of <tt>HashMap</tt>, due to the added expense of maintaining the 88 * linked list, with one exception: Iteration over the collection-views 89 * of a <tt>LinkedHashMap</tt> requires time proportional to the <i>size</i> 90 * of the map, regardless of its capacity. Iteration over a <tt>HashMap</tt> 91 * is likely to be more expensive, requiring time proportional to its 92 * <i>capacity</i>. 93 * 94 * <p>A linked hash map has two parameters that affect its performance: 95 * <i>initial capacity</i> and <i>load factor</i>. They are defined precisely 96 * as for <tt>HashMap</tt>. Note, however, that the penalty for choosing an 97 * excessively high value for initial capacity is less severe for this class 98 * than for <tt>HashMap</tt>, as iteration times for this class are unaffected 99 * by capacity. 100 * 101 * <p><strong>Note that this implementation is not synchronized.</strong> 102 * If multiple threads access a linked hash map concurrently, and at least 103 * one of the threads modifies the map structurally, it <em>must</em> be 104 * synchronized externally. This is typically accomplished by 105 * synchronizing on some object that naturally encapsulates the map. 106 * 107 * If no such object exists, the map should be "wrapped" using the 108 * {@link Collections#synchronizedMap Collections.synchronizedMap} 109 * method. This is best done at creation time, to prevent accidental 110 * unsynchronized access to the map:<pre> 111 * Map m = Collections.synchronizedMap(new LinkedHashMap(...));</pre> 112 * 113 * A structural modification is any operation that adds or deletes one or more 114 * mappings or, in the case of access-ordered linked hash maps, affects 115 * iteration order. In insertion-ordered linked hash maps, merely changing 116 * the value associated with a key that is already contained in the map is not 117 * a structural modification. <strong>In access-ordered linked hash maps, 118 * merely querying the map with <tt>get</tt> is a structural modification. 119 * </strong>) 120 * 121 * <p>The iterators returned by the <tt>iterator</tt> method of the collections 122 * returned by all of this class's collection view methods are 123 * <em>fail-fast</em>: if the map is structurally modified at any time after 124 * the iterator is created, in any way except through the iterator's own 125 * <tt>remove</tt> method, the iterator will throw a {@link 126 * ConcurrentModificationException}. Thus, in the face of concurrent 127 * modification, the iterator fails quickly and cleanly, rather than risking 128 * arbitrary, non-deterministic behavior at an undetermined time in the future. 129 * 130 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed 131 * as it is, generally speaking, impossible to make any hard guarantees in the 132 * presence of unsynchronized concurrent modification. Fail-fast iterators 133 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. 134 * Therefore, it would be wrong to write a program that depended on this 135 * exception for its correctness: <i>the fail-fast behavior of iterators 136 * should be used only to detect bugs.</i> 137 * 138 * <p>The spliterators returned by the spliterator method of the collections 139 * returned by all of this class's collection view methods are 140 * <em><a href="Spliterator.html#binding">late-binding</a></em>, 141 * <em>fail-fast</em>, and additionally report {@link Spliterator#ORDERED}. 142 * <em>Note</em>: The implementation of these spliterators in Android Nougat 143 * (API levels 24 and 25) uses the wrong order (inconsistent with the 144 * iterators, which use the correct order), despite reporting 145 * {@link Spliterator#ORDERED}. You may use the following code fragments 146 * to obtain a correctly ordered Spliterator on API level 24 and 25: 147 * <ul> 148 * <li>For a Collection view {@code c = lhm.keySet()}, 149 * {@code c = lhm.entrySet()} or {@code c = lhm.values()}, use 150 * {@code java.util.Spliterators.spliterator(c, c.spliterator().characteristics())} 151 * instead of {@code c.spliterator()}. 152 * <li>Instead of {@code c.stream()} or {@code c.parallelStream()}, use 153 * {@code java.util.stream.StreamSupport.stream(spliterator, false)} 154 * to construct a (nonparallel) {@link java.util.stream.Stream} from 155 * such a {@code Spliterator}. 156 * </ul> 157 * Note that these workarounds are only suggested where {@code lhm} is a 158 * {@code LinkedHashMap}. 159 * 160 * <p>This class is a member of the 161 * <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/collections/index.html"> 162 * Java Collections Framework</a>. 163 * 164 * @implNote 165 * The spliterators returned by the spliterator method of the collections 166 * returned by all of this class's collection view methods are created from 167 * the iterators of the corresponding collections. 168 * 169 * @param <K> the type of keys maintained by this map 170 * @param <V> the type of mapped values 171 * 172 * @author Josh Bloch 173 * @see Object#hashCode() 174 * @see Collection 175 * @see Map 176 * @see HashMap 177 * @see TreeMap 178 * @see Hashtable 179 * @since 1.4 180 */ 181 public class LinkedHashMap<K,V> 182 extends HashMap<K,V> 183 implements Map<K,V> 184 { 185 186 /* 187 * Implementation note. A previous version of this class was 188 * internally structured a little differently. Because superclass 189 * HashMap now uses trees for some of its nodes, class 190 * LinkedHashMap.Entry is now treated as intermediary node class 191 * that can also be converted to tree form. 192 * 193 // BEGIN Android-changed 194 * LinkedHashMapEntry should not be renamed. Specifically, for 195 * source compatibility with earlier versions of Android, this 196 * nested class must not be named "Entry". Otherwise, it would 197 * hide Map.Entry which would break compilation of code like: 198 * 199 * LinkedHashMap.Entry<K, V> entry = map.entrySet().iterator.next() 200 * 201 * To compile, that code snippet's "LinkedHashMap.Entry" must 202 * mean java.util.Map.Entry which is the compile time type of 203 * entrySet()'s elements. 204 // END Android-changed 205 * 206 * The changes in node classes also require using two fields 207 * (head, tail) rather than a pointer to a header node to maintain 208 * the doubly-linked before/after list. This class also 209 * previously used a different style of callback methods upon 210 * access, insertion, and removal. 211 */ 212 213 /** 214 * HashMap.Node subclass for normal LinkedHashMap entries. 215 */ 216 static class LinkedHashMapEntry<K,V> extends HashMap.Node<K,V> { 217 LinkedHashMapEntry<K,V> before, after; LinkedHashMapEntry(int hash, K key, V value, Node<K,V> next)218 LinkedHashMapEntry(int hash, K key, V value, Node<K,V> next) { 219 super(hash, key, value, next); 220 } 221 } 222 223 private static final long serialVersionUID = 3801124242820219131L; 224 225 /** 226 * The head (eldest) of the doubly linked list. 227 */ 228 transient LinkedHashMapEntry<K,V> head; 229 230 /** 231 * The tail (youngest) of the doubly linked list. 232 */ 233 transient LinkedHashMapEntry<K,V> tail; 234 235 /** 236 * The iteration ordering method for this linked hash map: <tt>true</tt> 237 * for access-order, <tt>false</tt> for insertion-order. 238 * 239 * @serial 240 */ 241 final boolean accessOrder; 242 243 // internal utilities 244 245 // link at the end of list linkNodeLast(LinkedHashMapEntry<K,V> p)246 private void linkNodeLast(LinkedHashMapEntry<K,V> p) { 247 LinkedHashMapEntry<K,V> last = tail; 248 tail = p; 249 if (last == null) 250 head = p; 251 else { 252 p.before = last; 253 last.after = p; 254 } 255 } 256 257 // apply src's links to dst transferLinks(LinkedHashMapEntry<K,V> src, LinkedHashMapEntry<K,V> dst)258 private void transferLinks(LinkedHashMapEntry<K,V> src, 259 LinkedHashMapEntry<K,V> dst) { 260 LinkedHashMapEntry<K,V> b = dst.before = src.before; 261 LinkedHashMapEntry<K,V> a = dst.after = src.after; 262 if (b == null) 263 head = dst; 264 else 265 b.after = dst; 266 if (a == null) 267 tail = dst; 268 else 269 a.before = dst; 270 } 271 272 // overrides of HashMap hook methods 273 reinitialize()274 void reinitialize() { 275 super.reinitialize(); 276 head = tail = null; 277 } 278 newNode(int hash, K key, V value, Node<K,V> e)279 Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) { 280 LinkedHashMapEntry<K,V> p = 281 new LinkedHashMapEntry<K,V>(hash, key, value, e); 282 linkNodeLast(p); 283 return p; 284 } 285 replacementNode(Node<K,V> p, Node<K,V> next)286 Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) { 287 LinkedHashMapEntry<K,V> q = (LinkedHashMapEntry<K,V>)p; 288 LinkedHashMapEntry<K,V> t = 289 new LinkedHashMapEntry<K,V>(q.hash, q.key, q.value, next); 290 transferLinks(q, t); 291 return t; 292 } 293 newTreeNode(int hash, K key, V value, Node<K,V> next)294 TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) { 295 TreeNode<K,V> p = new TreeNode<K,V>(hash, key, value, next); 296 linkNodeLast(p); 297 return p; 298 } 299 replacementTreeNode(Node<K,V> p, Node<K,V> next)300 TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) { 301 LinkedHashMapEntry<K,V> q = (LinkedHashMapEntry<K,V>)p; 302 TreeNode<K,V> t = new TreeNode<K,V>(q.hash, q.key, q.value, next); 303 transferLinks(q, t); 304 return t; 305 } 306 afterNodeRemoval(Node<K,V> e)307 void afterNodeRemoval(Node<K,V> e) { // unlink 308 LinkedHashMapEntry<K,V> p = 309 (LinkedHashMapEntry<K,V>)e, b = p.before, a = p.after; 310 p.before = p.after = null; 311 if (b == null) 312 head = a; 313 else 314 b.after = a; 315 if (a == null) 316 tail = b; 317 else 318 a.before = b; 319 } 320 afterNodeInsertion(boolean evict)321 void afterNodeInsertion(boolean evict) { // possibly remove eldest 322 LinkedHashMapEntry<K,V> first; 323 if (evict && (first = head) != null && removeEldestEntry(first)) { 324 K key = first.key; 325 removeNode(hash(key), key, null, false, true); 326 } 327 } 328 afterNodeAccess(Node<K,V> e)329 void afterNodeAccess(Node<K,V> e) { // move node to last 330 LinkedHashMapEntry<K,V> last; 331 if (accessOrder && (last = tail) != e) { 332 LinkedHashMapEntry<K,V> p = 333 (LinkedHashMapEntry<K,V>)e, b = p.before, a = p.after; 334 p.after = null; 335 if (b == null) 336 head = a; 337 else 338 b.after = a; 339 if (a != null) 340 a.before = b; 341 else 342 last = b; 343 if (last == null) 344 head = p; 345 else { 346 p.before = last; 347 last.after = p; 348 } 349 tail = p; 350 ++modCount; 351 } 352 } 353 internalWriteEntries(java.io.ObjectOutputStream s)354 void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException { 355 for (LinkedHashMapEntry<K,V> e = head; e != null; e = e.after) { 356 s.writeObject(e.key); 357 s.writeObject(e.value); 358 } 359 } 360 361 /** 362 * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance 363 * with the specified initial capacity and load factor. 364 * 365 * @param initialCapacity the initial capacity 366 * @param loadFactor the load factor 367 * @throws IllegalArgumentException if the initial capacity is negative 368 * or the load factor is nonpositive 369 */ LinkedHashMap(int initialCapacity, float loadFactor)370 public LinkedHashMap(int initialCapacity, float loadFactor) { 371 super(initialCapacity, loadFactor); 372 accessOrder = false; 373 } 374 375 /** 376 * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance 377 * with the specified initial capacity and a default load factor (0.75). 378 * 379 * @param initialCapacity the initial capacity 380 * @throws IllegalArgumentException if the initial capacity is negative 381 */ LinkedHashMap(int initialCapacity)382 public LinkedHashMap(int initialCapacity) { 383 super(initialCapacity); 384 accessOrder = false; 385 } 386 387 /** 388 * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance 389 * with the default initial capacity (16) and load factor (0.75). 390 */ LinkedHashMap()391 public LinkedHashMap() { 392 super(); 393 accessOrder = false; 394 } 395 396 /** 397 * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with 398 * the same mappings as the specified map. The <tt>LinkedHashMap</tt> 399 * instance is created with a default load factor (0.75) and an initial 400 * capacity sufficient to hold the mappings in the specified map. 401 * 402 * @param m the map whose mappings are to be placed in this map 403 * @throws NullPointerException if the specified map is null 404 */ LinkedHashMap(Map<? extends K, ? extends V> m)405 public LinkedHashMap(Map<? extends K, ? extends V> m) { 406 super(); 407 accessOrder = false; 408 putMapEntries(m, false); 409 } 410 411 /** 412 * Constructs an empty <tt>LinkedHashMap</tt> instance with the 413 * specified initial capacity, load factor and ordering mode. 414 * 415 * @param initialCapacity the initial capacity 416 * @param loadFactor the load factor 417 * @param accessOrder the ordering mode - <tt>true</tt> for 418 * access-order, <tt>false</tt> for insertion-order 419 * @throws IllegalArgumentException if the initial capacity is negative 420 * or the load factor is nonpositive 421 */ LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)422 public LinkedHashMap(int initialCapacity, 423 float loadFactor, 424 boolean accessOrder) { 425 super(initialCapacity, loadFactor); 426 this.accessOrder = accessOrder; 427 } 428 429 430 /** 431 * Returns <tt>true</tt> if this map maps one or more keys to the 432 * specified value. 433 * 434 * @param value value whose presence in this map is to be tested 435 * @return <tt>true</tt> if this map maps one or more keys to the 436 * specified value 437 */ containsValue(Object value)438 public boolean containsValue(Object value) { 439 for (LinkedHashMapEntry<K,V> e = head; e != null; e = e.after) { 440 V v = e.value; 441 if (v == value || (value != null && value.equals(v))) 442 return true; 443 } 444 return false; 445 } 446 447 /** 448 * Returns the value to which the specified key is mapped, 449 * or {@code null} if this map contains no mapping for the key. 450 * 451 * <p>More formally, if this map contains a mapping from a key 452 * {@code k} to a value {@code v} such that {@code (key==null ? k==null : 453 * key.equals(k))}, then this method returns {@code v}; otherwise 454 * it returns {@code null}. (There can be at most one such mapping.) 455 * 456 * <p>A return value of {@code null} does not <i>necessarily</i> 457 * indicate that the map contains no mapping for the key; it's also 458 * possible that the map explicitly maps the key to {@code null}. 459 * The {@link #containsKey containsKey} operation may be used to 460 * distinguish these two cases. 461 */ get(Object key)462 public V get(Object key) { 463 Node<K,V> e; 464 if ((e = getNode(hash(key), key)) == null) 465 return null; 466 if (accessOrder) 467 afterNodeAccess(e); 468 return e.value; 469 } 470 471 /** 472 * {@inheritDoc} 473 */ getOrDefault(Object key, V defaultValue)474 public V getOrDefault(Object key, V defaultValue) { 475 Node<K,V> e; 476 if ((e = getNode(hash(key), key)) == null) 477 return defaultValue; 478 if (accessOrder) 479 afterNodeAccess(e); 480 return e.value; 481 } 482 483 /** 484 * {@inheritDoc} 485 */ clear()486 public void clear() { 487 super.clear(); 488 head = tail = null; 489 } 490 491 // Android-added: eldest(), for internal use in LRU caches 492 /** 493 * Returns the eldest entry in the map, or {@code null} if the map is empty. 494 * 495 * @return eldest entry in the map, or {@code null} if the map is empty 496 * 497 * @hide 498 */ eldest()499 public Map.Entry<K, V> eldest() { 500 return head; 501 } 502 503 /** 504 * Returns <tt>true</tt> if this map should remove its eldest entry. 505 * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after 506 * inserting a new entry into the map. It provides the implementor 507 * with the opportunity to remove the eldest entry each time a new one 508 * is added. This is useful if the map represents a cache: it allows 509 * the map to reduce memory consumption by deleting stale entries. 510 * 511 * <p>Sample use: this override will allow the map to grow up to 100 512 * entries and then delete the eldest entry each time a new entry is 513 * added, maintaining a steady state of 100 entries. 514 * <pre> 515 * private static final int MAX_ENTRIES = 100; 516 * 517 * protected boolean removeEldestEntry(Map.Entry eldest) { 518 * return size() > MAX_ENTRIES; 519 * } 520 * </pre> 521 * 522 * <p>This method typically does not modify the map in any way, 523 * instead allowing the map to modify itself as directed by its 524 * return value. It <i>is</i> permitted for this method to modify 525 * the map directly, but if it does so, it <i>must</i> return 526 * <tt>false</tt> (indicating that the map should not attempt any 527 * further modification). The effects of returning <tt>true</tt> 528 * after modifying the map from within this method are unspecified. 529 * 530 * <p>This implementation merely returns <tt>false</tt> (so that this 531 * map acts like a normal map - the eldest element is never removed). 532 * 533 * @param eldest The least recently inserted entry in the map, or if 534 * this is an access-ordered map, the least recently accessed 535 * entry. This is the entry that will be removed it this 536 * method returns <tt>true</tt>. If the map was empty prior 537 * to the <tt>put</tt> or <tt>putAll</tt> invocation resulting 538 * in this invocation, this will be the entry that was just 539 * inserted; in other words, if the map contains a single 540 * entry, the eldest entry is also the newest. 541 * @return <tt>true</tt> if the eldest entry should be removed 542 * from the map; <tt>false</tt> if it should be retained. 543 */ removeEldestEntry(Map.Entry<K,V> eldest)544 protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { 545 return false; 546 } 547 548 /** 549 * Returns a {@link Set} view of the keys contained in this map. 550 * The set is backed by the map, so changes to the map are 551 * reflected in the set, and vice-versa. If the map is modified 552 * while an iteration over the set is in progress (except through 553 * the iterator's own <tt>remove</tt> operation), the results of 554 * the iteration are undefined. The set supports element removal, 555 * which removes the corresponding mapping from the map, via the 556 * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, 557 * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> 558 * operations. It does not support the <tt>add</tt> or <tt>addAll</tt> 559 * operations. 560 * Its {@link Spliterator} typically provides faster sequential 561 * performance but much poorer parallel performance than that of 562 * {@code HashMap}. 563 * 564 * @return a set view of the keys contained in this map 565 */ keySet()566 public Set<K> keySet() { 567 Set<K> ks = keySet; 568 if (ks == null) { 569 ks = new LinkedKeySet(); 570 keySet = ks; 571 } 572 return ks; 573 } 574 575 final class LinkedKeySet extends AbstractSet<K> { size()576 public final int size() { return size; } clear()577 public final void clear() { LinkedHashMap.this.clear(); } iterator()578 public final Iterator<K> iterator() { 579 return new LinkedKeyIterator(); 580 } contains(Object o)581 public final boolean contains(Object o) { return containsKey(o); } remove(Object key)582 public final boolean remove(Object key) { 583 return removeNode(hash(key), key, null, false, true) != null; 584 } spliterator()585 public final Spliterator<K> spliterator() { 586 return Spliterators.spliterator(this, Spliterator.SIZED | 587 Spliterator.ORDERED | 588 Spliterator.DISTINCT); 589 } forEach(Consumer<? super K> action)590 public final void forEach(Consumer<? super K> action) { 591 if (action == null) 592 throw new NullPointerException(); 593 int mc = modCount; 594 // Android-changed: Detect changes to modCount early. 595 for (LinkedHashMapEntry<K,V> e = head; (e != null && modCount == mc); e = e.after) 596 action.accept(e.key); 597 if (modCount != mc) 598 throw new ConcurrentModificationException(); 599 } 600 } 601 602 /** 603 * Returns a {@link Collection} view of the values contained in this map. 604 * The collection is backed by the map, so changes to the map are 605 * reflected in the collection, and vice-versa. If the map is 606 * modified while an iteration over the collection is in progress 607 * (except through the iterator's own <tt>remove</tt> operation), 608 * the results of the iteration are undefined. The collection 609 * supports element removal, which removes the corresponding 610 * mapping from the map, via the <tt>Iterator.remove</tt>, 611 * <tt>Collection.remove</tt>, <tt>removeAll</tt>, 612 * <tt>retainAll</tt> and <tt>clear</tt> operations. It does not 613 * support the <tt>add</tt> or <tt>addAll</tt> operations. 614 * Its {@link Spliterator} typically provides faster sequential 615 * performance but much poorer parallel performance than that of 616 * {@code HashMap}. 617 * 618 * @return a view of the values contained in this map 619 */ values()620 public Collection<V> values() { 621 Collection<V> vs = values; 622 if (vs == null) { 623 vs = new LinkedValues(); 624 values = vs; 625 } 626 return vs; 627 } 628 629 final class LinkedValues extends AbstractCollection<V> { size()630 public final int size() { return size; } clear()631 public final void clear() { LinkedHashMap.this.clear(); } iterator()632 public final Iterator<V> iterator() { 633 return new LinkedValueIterator(); 634 } contains(Object o)635 public final boolean contains(Object o) { return containsValue(o); } spliterator()636 public final Spliterator<V> spliterator() { 637 return Spliterators.spliterator(this, Spliterator.SIZED | 638 Spliterator.ORDERED); 639 } forEach(Consumer<? super V> action)640 public final void forEach(Consumer<? super V> action) { 641 if (action == null) 642 throw new NullPointerException(); 643 int mc = modCount; 644 // Android-changed: Detect changes to modCount early. 645 for (LinkedHashMapEntry<K,V> e = head; (e != null && modCount == mc); e = e.after) 646 action.accept(e.value); 647 if (modCount != mc) 648 throw new ConcurrentModificationException(); 649 } 650 } 651 652 /** 653 * Returns a {@link Set} view of the mappings contained in this map. 654 * The set is backed by the map, so changes to the map are 655 * reflected in the set, and vice-versa. If the map is modified 656 * while an iteration over the set is in progress (except through 657 * the iterator's own <tt>remove</tt> operation, or through the 658 * <tt>setValue</tt> operation on a map entry returned by the 659 * iterator) the results of the iteration are undefined. The set 660 * supports element removal, which removes the corresponding 661 * mapping from the map, via the <tt>Iterator.remove</tt>, 662 * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and 663 * <tt>clear</tt> operations. It does not support the 664 * <tt>add</tt> or <tt>addAll</tt> operations. 665 * Its {@link Spliterator} typically provides faster sequential 666 * performance but much poorer parallel performance than that of 667 * {@code HashMap}. 668 * 669 * @return a set view of the mappings contained in this map 670 */ entrySet()671 public Set<Map.Entry<K,V>> entrySet() { 672 Set<Map.Entry<K,V>> es; 673 return (es = entrySet) == null ? (entrySet = new LinkedEntrySet()) : es; 674 } 675 676 final class LinkedEntrySet extends AbstractSet<Map.Entry<K,V>> { size()677 public final int size() { return size; } clear()678 public final void clear() { LinkedHashMap.this.clear(); } iterator()679 public final Iterator<Map.Entry<K,V>> iterator() { 680 return new LinkedEntryIterator(); 681 } contains(Object o)682 public final boolean contains(Object o) { 683 if (!(o instanceof Map.Entry)) 684 return false; 685 Map.Entry<?,?> e = (Map.Entry<?,?>) o; 686 Object key = e.getKey(); 687 Node<K,V> candidate = getNode(hash(key), key); 688 return candidate != null && candidate.equals(e); 689 } remove(Object o)690 public final boolean remove(Object o) { 691 if (o instanceof Map.Entry) { 692 Map.Entry<?,?> e = (Map.Entry<?,?>) o; 693 Object key = e.getKey(); 694 Object value = e.getValue(); 695 return removeNode(hash(key), key, value, true, true) != null; 696 } 697 return false; 698 } spliterator()699 public final Spliterator<Map.Entry<K,V>> spliterator() { 700 return Spliterators.spliterator(this, Spliterator.SIZED | 701 Spliterator.ORDERED | 702 Spliterator.DISTINCT); 703 } forEach(Consumer<? super Map.Entry<K,V>> action)704 public final void forEach(Consumer<? super Map.Entry<K,V>> action) { 705 if (action == null) 706 throw new NullPointerException(); 707 int mc = modCount; 708 // Android-changed: Detect changes to modCount early. 709 for (LinkedHashMapEntry<K,V> e = head; (e != null && mc == modCount); e = e.after) 710 action.accept(e); 711 if (modCount != mc) 712 throw new ConcurrentModificationException(); 713 } 714 } 715 716 // Map overrides 717 forEach(BiConsumer<? super K, ? super V> action)718 public void forEach(BiConsumer<? super K, ? super V> action) { 719 if (action == null) 720 throw new NullPointerException(); 721 int mc = modCount; 722 // Android-changed: Detect changes to modCount early. 723 for (LinkedHashMapEntry<K,V> e = head; modCount == mc && e != null; e = e.after) 724 action.accept(e.key, e.value); 725 if (modCount != mc) 726 throw new ConcurrentModificationException(); 727 } 728 replaceAll(BiFunction<? super K, ? super V, ? extends V> function)729 public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { 730 if (function == null) 731 throw new NullPointerException(); 732 int mc = modCount; 733 // Android-changed: Detect changes to modCount early. 734 for (LinkedHashMapEntry<K,V> e = head; modCount == mc && e != null; e = e.after) 735 e.value = function.apply(e.key, e.value); 736 if (modCount != mc) 737 throw new ConcurrentModificationException(); 738 } 739 740 // Iterators 741 742 abstract class LinkedHashIterator { 743 LinkedHashMapEntry<K,V> next; 744 LinkedHashMapEntry<K,V> current; 745 int expectedModCount; 746 LinkedHashIterator()747 LinkedHashIterator() { 748 next = head; 749 expectedModCount = modCount; 750 current = null; 751 } 752 hasNext()753 public final boolean hasNext() { 754 return next != null; 755 } 756 nextNode()757 final LinkedHashMapEntry<K,V> nextNode() { 758 LinkedHashMapEntry<K,V> e = next; 759 if (modCount != expectedModCount) 760 throw new ConcurrentModificationException(); 761 if (e == null) 762 throw new NoSuchElementException(); 763 current = e; 764 next = e.after; 765 return e; 766 } 767 remove()768 public final void remove() { 769 Node<K,V> p = current; 770 if (p == null) 771 throw new IllegalStateException(); 772 if (modCount != expectedModCount) 773 throw new ConcurrentModificationException(); 774 current = null; 775 K key = p.key; 776 removeNode(hash(key), key, null, false, false); 777 expectedModCount = modCount; 778 } 779 } 780 781 final class LinkedKeyIterator extends LinkedHashIterator 782 implements Iterator<K> { next()783 public final K next() { return nextNode().getKey(); } 784 } 785 786 final class LinkedValueIterator extends LinkedHashIterator 787 implements Iterator<V> { next()788 public final V next() { return nextNode().value; } 789 } 790 791 final class LinkedEntryIterator extends LinkedHashIterator 792 implements Iterator<Map.Entry<K,V>> { next()793 public final Map.Entry<K,V> next() { return nextNode(); } 794 } 795 796 797 } 798