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