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