1.1 --- a/emul/compact/src/main/java/java/util/LinkedHashMap.java Mon Feb 25 19:00:08 2013 +0100
1.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
1.3 @@ -1,491 +0,0 @@
1.4 -/*
1.5 - * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
1.6 - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1.7 - *
1.8 - * This code is free software; you can redistribute it and/or modify it
1.9 - * under the terms of the GNU General Public License version 2 only, as
1.10 - * published by the Free Software Foundation. Oracle designates this
1.11 - * particular file as subject to the "Classpath" exception as provided
1.12 - * by Oracle in the LICENSE file that accompanied this code.
1.13 - *
1.14 - * This code is distributed in the hope that it will be useful, but WITHOUT
1.15 - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1.16 - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1.17 - * version 2 for more details (a copy is included in the LICENSE file that
1.18 - * accompanied this code).
1.19 - *
1.20 - * You should have received a copy of the GNU General Public License version
1.21 - * 2 along with this work; if not, write to the Free Software Foundation,
1.22 - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1.23 - *
1.24 - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1.25 - * or visit www.oracle.com if you need additional information or have any
1.26 - * questions.
1.27 - */
1.28 -
1.29 -package java.util;
1.30 -import java.io.*;
1.31 -
1.32 -/**
1.33 - * <p>Hash table and linked list implementation of the <tt>Map</tt> interface,
1.34 - * with predictable iteration order. This implementation differs from
1.35 - * <tt>HashMap</tt> in that it maintains a doubly-linked list running through
1.36 - * all of its entries. This linked list defines the iteration ordering,
1.37 - * which is normally the order in which keys were inserted into the map
1.38 - * (<i>insertion-order</i>). Note that insertion order is not affected
1.39 - * if a key is <i>re-inserted</i> into the map. (A key <tt>k</tt> is
1.40 - * reinserted into a map <tt>m</tt> if <tt>m.put(k, v)</tt> is invoked when
1.41 - * <tt>m.containsKey(k)</tt> would return <tt>true</tt> immediately prior to
1.42 - * the invocation.)
1.43 - *
1.44 - * <p>This implementation spares its clients from the unspecified, generally
1.45 - * chaotic ordering provided by {@link HashMap} (and {@link Hashtable}),
1.46 - * without incurring the increased cost associated with {@link TreeMap}. It
1.47 - * can be used to produce a copy of a map that has the same order as the
1.48 - * original, regardless of the original map's implementation:
1.49 - * <pre>
1.50 - * void foo(Map m) {
1.51 - * Map copy = new LinkedHashMap(m);
1.52 - * ...
1.53 - * }
1.54 - * </pre>
1.55 - * This technique is particularly useful if a module takes a map on input,
1.56 - * copies it, and later returns results whose order is determined by that of
1.57 - * the copy. (Clients generally appreciate having things returned in the same
1.58 - * order they were presented.)
1.59 - *
1.60 - * <p>A special {@link #LinkedHashMap(int,float,boolean) constructor} is
1.61 - * provided to create a linked hash map whose order of iteration is the order
1.62 - * in which its entries were last accessed, from least-recently accessed to
1.63 - * most-recently (<i>access-order</i>). This kind of map is well-suited to
1.64 - * building LRU caches. Invoking the <tt>put</tt> or <tt>get</tt> method
1.65 - * results in an access to the corresponding entry (assuming it exists after
1.66 - * the invocation completes). The <tt>putAll</tt> method generates one entry
1.67 - * access for each mapping in the specified map, in the order that key-value
1.68 - * mappings are provided by the specified map's entry set iterator. <i>No
1.69 - * other methods generate entry accesses.</i> In particular, operations on
1.70 - * collection-views do <i>not</i> affect the order of iteration of the backing
1.71 - * map.
1.72 - *
1.73 - * <p>The {@link #removeEldestEntry(Map.Entry)} method may be overridden to
1.74 - * impose a policy for removing stale mappings automatically when new mappings
1.75 - * are added to the map.
1.76 - *
1.77 - * <p>This class provides all of the optional <tt>Map</tt> operations, and
1.78 - * permits null elements. Like <tt>HashMap</tt>, it provides constant-time
1.79 - * performance for the basic operations (<tt>add</tt>, <tt>contains</tt> and
1.80 - * <tt>remove</tt>), assuming the hash function disperses elements
1.81 - * properly among the buckets. Performance is likely to be just slightly
1.82 - * below that of <tt>HashMap</tt>, due to the added expense of maintaining the
1.83 - * linked list, with one exception: Iteration over the collection-views
1.84 - * of a <tt>LinkedHashMap</tt> requires time proportional to the <i>size</i>
1.85 - * of the map, regardless of its capacity. Iteration over a <tt>HashMap</tt>
1.86 - * is likely to be more expensive, requiring time proportional to its
1.87 - * <i>capacity</i>.
1.88 - *
1.89 - * <p>A linked hash map has two parameters that affect its performance:
1.90 - * <i>initial capacity</i> and <i>load factor</i>. They are defined precisely
1.91 - * as for <tt>HashMap</tt>. Note, however, that the penalty for choosing an
1.92 - * excessively high value for initial capacity is less severe for this class
1.93 - * than for <tt>HashMap</tt>, as iteration times for this class are unaffected
1.94 - * by capacity.
1.95 - *
1.96 - * <p><strong>Note that this implementation is not synchronized.</strong>
1.97 - * If multiple threads access a linked hash map concurrently, and at least
1.98 - * one of the threads modifies the map structurally, it <em>must</em> be
1.99 - * synchronized externally. This is typically accomplished by
1.100 - * synchronizing on some object that naturally encapsulates the map.
1.101 - *
1.102 - * If no such object exists, the map should be "wrapped" using the
1.103 - * {@link Collections#synchronizedMap Collections.synchronizedMap}
1.104 - * method. This is best done at creation time, to prevent accidental
1.105 - * unsynchronized access to the map:<pre>
1.106 - * Map m = Collections.synchronizedMap(new LinkedHashMap(...));</pre>
1.107 - *
1.108 - * A structural modification is any operation that adds or deletes one or more
1.109 - * mappings or, in the case of access-ordered linked hash maps, affects
1.110 - * iteration order. In insertion-ordered linked hash maps, merely changing
1.111 - * the value associated with a key that is already contained in the map is not
1.112 - * a structural modification. <strong>In access-ordered linked hash maps,
1.113 - * merely querying the map with <tt>get</tt> is a structural
1.114 - * modification.</strong>)
1.115 - *
1.116 - * <p>The iterators returned by the <tt>iterator</tt> method of the collections
1.117 - * returned by all of this class's collection view methods are
1.118 - * <em>fail-fast</em>: if the map is structurally modified at any time after
1.119 - * the iterator is created, in any way except through the iterator's own
1.120 - * <tt>remove</tt> method, the iterator will throw a {@link
1.121 - * ConcurrentModificationException}. Thus, in the face of concurrent
1.122 - * modification, the iterator fails quickly and cleanly, rather than risking
1.123 - * arbitrary, non-deterministic behavior at an undetermined time in the future.
1.124 - *
1.125 - * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
1.126 - * as it is, generally speaking, impossible to make any hard guarantees in the
1.127 - * presence of unsynchronized concurrent modification. Fail-fast iterators
1.128 - * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
1.129 - * Therefore, it would be wrong to write a program that depended on this
1.130 - * exception for its correctness: <i>the fail-fast behavior of iterators
1.131 - * should be used only to detect bugs.</i>
1.132 - *
1.133 - * <p>This class is a member of the
1.134 - * <a href="{@docRoot}/../technotes/guides/collections/index.html">
1.135 - * Java Collections Framework</a>.
1.136 - *
1.137 - * @param <K> the type of keys maintained by this map
1.138 - * @param <V> the type of mapped values
1.139 - *
1.140 - * @author Josh Bloch
1.141 - * @see Object#hashCode()
1.142 - * @see Collection
1.143 - * @see Map
1.144 - * @see HashMap
1.145 - * @see TreeMap
1.146 - * @see Hashtable
1.147 - * @since 1.4
1.148 - */
1.149 -
1.150 -public class LinkedHashMap<K,V>
1.151 - extends HashMap<K,V>
1.152 - implements Map<K,V>
1.153 -{
1.154 -
1.155 - private static final long serialVersionUID = 3801124242820219131L;
1.156 -
1.157 - /**
1.158 - * The head of the doubly linked list.
1.159 - */
1.160 - private transient Entry<K,V> header;
1.161 -
1.162 - /**
1.163 - * The iteration ordering method for this linked hash map: <tt>true</tt>
1.164 - * for access-order, <tt>false</tt> for insertion-order.
1.165 - *
1.166 - * @serial
1.167 - */
1.168 - private final boolean accessOrder;
1.169 -
1.170 - /**
1.171 - * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
1.172 - * with the specified initial capacity and load factor.
1.173 - *
1.174 - * @param initialCapacity the initial capacity
1.175 - * @param loadFactor the load factor
1.176 - * @throws IllegalArgumentException if the initial capacity is negative
1.177 - * or the load factor is nonpositive
1.178 - */
1.179 - public LinkedHashMap(int initialCapacity, float loadFactor) {
1.180 - super(initialCapacity, loadFactor);
1.181 - accessOrder = false;
1.182 - }
1.183 -
1.184 - /**
1.185 - * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
1.186 - * with the specified initial capacity and a default load factor (0.75).
1.187 - *
1.188 - * @param initialCapacity the initial capacity
1.189 - * @throws IllegalArgumentException if the initial capacity is negative
1.190 - */
1.191 - public LinkedHashMap(int initialCapacity) {
1.192 - super(initialCapacity);
1.193 - accessOrder = false;
1.194 - }
1.195 -
1.196 - /**
1.197 - * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
1.198 - * with the default initial capacity (16) and load factor (0.75).
1.199 - */
1.200 - public LinkedHashMap() {
1.201 - super();
1.202 - accessOrder = false;
1.203 - }
1.204 -
1.205 - /**
1.206 - * Constructs an insertion-ordered <tt>LinkedHashMap</tt> instance with
1.207 - * the same mappings as the specified map. The <tt>LinkedHashMap</tt>
1.208 - * instance is created with a default load factor (0.75) and an initial
1.209 - * capacity sufficient to hold the mappings in the specified map.
1.210 - *
1.211 - * @param m the map whose mappings are to be placed in this map
1.212 - * @throws NullPointerException if the specified map is null
1.213 - */
1.214 - public LinkedHashMap(Map<? extends K, ? extends V> m) {
1.215 - super(m);
1.216 - accessOrder = false;
1.217 - }
1.218 -
1.219 - /**
1.220 - * Constructs an empty <tt>LinkedHashMap</tt> instance with the
1.221 - * specified initial capacity, load factor and ordering mode.
1.222 - *
1.223 - * @param initialCapacity the initial capacity
1.224 - * @param loadFactor the load factor
1.225 - * @param accessOrder the ordering mode - <tt>true</tt> for
1.226 - * access-order, <tt>false</tt> for insertion-order
1.227 - * @throws IllegalArgumentException if the initial capacity is negative
1.228 - * or the load factor is nonpositive
1.229 - */
1.230 - public LinkedHashMap(int initialCapacity,
1.231 - float loadFactor,
1.232 - boolean accessOrder) {
1.233 - super(initialCapacity, loadFactor);
1.234 - this.accessOrder = accessOrder;
1.235 - }
1.236 -
1.237 - /**
1.238 - * Called by superclass constructors and pseudoconstructors (clone,
1.239 - * readObject) before any entries are inserted into the map. Initializes
1.240 - * the chain.
1.241 - */
1.242 - void init() {
1.243 - header = new Entry<>(-1, null, null, null);
1.244 - header.before = header.after = header;
1.245 - }
1.246 -
1.247 - /**
1.248 - * Transfers all entries to new table array. This method is called
1.249 - * by superclass resize. It is overridden for performance, as it is
1.250 - * faster to iterate using our linked list.
1.251 - */
1.252 - void transfer(HashMap.Entry[] newTable) {
1.253 - int newCapacity = newTable.length;
1.254 - for (Entry<K,V> e = header.after; e != header; e = e.after) {
1.255 - int index = indexFor(e.hash, newCapacity);
1.256 - e.next = newTable[index];
1.257 - newTable[index] = e;
1.258 - }
1.259 - }
1.260 -
1.261 -
1.262 - /**
1.263 - * Returns <tt>true</tt> if this map maps one or more keys to the
1.264 - * specified value.
1.265 - *
1.266 - * @param value value whose presence in this map is to be tested
1.267 - * @return <tt>true</tt> if this map maps one or more keys to the
1.268 - * specified value
1.269 - */
1.270 - public boolean containsValue(Object value) {
1.271 - // Overridden to take advantage of faster iterator
1.272 - if (value==null) {
1.273 - for (Entry e = header.after; e != header; e = e.after)
1.274 - if (e.value==null)
1.275 - return true;
1.276 - } else {
1.277 - for (Entry e = header.after; e != header; e = e.after)
1.278 - if (value.equals(e.value))
1.279 - return true;
1.280 - }
1.281 - return false;
1.282 - }
1.283 -
1.284 - /**
1.285 - * Returns the value to which the specified key is mapped,
1.286 - * or {@code null} if this map contains no mapping for the key.
1.287 - *
1.288 - * <p>More formally, if this map contains a mapping from a key
1.289 - * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
1.290 - * key.equals(k))}, then this method returns {@code v}; otherwise
1.291 - * it returns {@code null}. (There can be at most one such mapping.)
1.292 - *
1.293 - * <p>A return value of {@code null} does not <i>necessarily</i>
1.294 - * indicate that the map contains no mapping for the key; it's also
1.295 - * possible that the map explicitly maps the key to {@code null}.
1.296 - * The {@link #containsKey containsKey} operation may be used to
1.297 - * distinguish these two cases.
1.298 - */
1.299 - public V get(Object key) {
1.300 - Entry<K,V> e = (Entry<K,V>)getEntry(key);
1.301 - if (e == null)
1.302 - return null;
1.303 - e.recordAccess(this);
1.304 - return e.value;
1.305 - }
1.306 -
1.307 - /**
1.308 - * Removes all of the mappings from this map.
1.309 - * The map will be empty after this call returns.
1.310 - */
1.311 - public void clear() {
1.312 - super.clear();
1.313 - header.before = header.after = header;
1.314 - }
1.315 -
1.316 - /**
1.317 - * LinkedHashMap entry.
1.318 - */
1.319 - private static class Entry<K,V> extends HashMap.Entry<K,V> {
1.320 - // These fields comprise the doubly linked list used for iteration.
1.321 - Entry<K,V> before, after;
1.322 -
1.323 - Entry(int hash, K key, V value, HashMap.Entry<K,V> next) {
1.324 - super(hash, key, value, next);
1.325 - }
1.326 -
1.327 - /**
1.328 - * Removes this entry from the linked list.
1.329 - */
1.330 - private void remove() {
1.331 - before.after = after;
1.332 - after.before = before;
1.333 - }
1.334 -
1.335 - /**
1.336 - * Inserts this entry before the specified existing entry in the list.
1.337 - */
1.338 - private void addBefore(Entry<K,V> existingEntry) {
1.339 - after = existingEntry;
1.340 - before = existingEntry.before;
1.341 - before.after = this;
1.342 - after.before = this;
1.343 - }
1.344 -
1.345 - /**
1.346 - * This method is invoked by the superclass whenever the value
1.347 - * of a pre-existing entry is read by Map.get or modified by Map.set.
1.348 - * If the enclosing Map is access-ordered, it moves the entry
1.349 - * to the end of the list; otherwise, it does nothing.
1.350 - */
1.351 - void recordAccess(HashMap<K,V> m) {
1.352 - LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
1.353 - if (lm.accessOrder) {
1.354 - lm.modCount++;
1.355 - remove();
1.356 - addBefore(lm.header);
1.357 - }
1.358 - }
1.359 -
1.360 - void recordRemoval(HashMap<K,V> m) {
1.361 - remove();
1.362 - }
1.363 - }
1.364 -
1.365 - private abstract class LinkedHashIterator<T> implements Iterator<T> {
1.366 - Entry<K,V> nextEntry = header.after;
1.367 - Entry<K,V> lastReturned = null;
1.368 -
1.369 - /**
1.370 - * The modCount value that the iterator believes that the backing
1.371 - * List should have. If this expectation is violated, the iterator
1.372 - * has detected concurrent modification.
1.373 - */
1.374 - int expectedModCount = modCount;
1.375 -
1.376 - public boolean hasNext() {
1.377 - return nextEntry != header;
1.378 - }
1.379 -
1.380 - public void remove() {
1.381 - if (lastReturned == null)
1.382 - throw new IllegalStateException();
1.383 - if (modCount != expectedModCount)
1.384 - throw new ConcurrentModificationException();
1.385 -
1.386 - LinkedHashMap.this.remove(lastReturned.key);
1.387 - lastReturned = null;
1.388 - expectedModCount = modCount;
1.389 - }
1.390 -
1.391 - Entry<K,V> nextEntry() {
1.392 - if (modCount != expectedModCount)
1.393 - throw new ConcurrentModificationException();
1.394 - if (nextEntry == header)
1.395 - throw new NoSuchElementException();
1.396 -
1.397 - Entry<K,V> e = lastReturned = nextEntry;
1.398 - nextEntry = e.after;
1.399 - return e;
1.400 - }
1.401 - }
1.402 -
1.403 - private class KeyIterator extends LinkedHashIterator<K> {
1.404 - public K next() { return nextEntry().getKey(); }
1.405 - }
1.406 -
1.407 - private class ValueIterator extends LinkedHashIterator<V> {
1.408 - public V next() { return nextEntry().value; }
1.409 - }
1.410 -
1.411 - private class EntryIterator extends LinkedHashIterator<Map.Entry<K,V>> {
1.412 - public Map.Entry<K,V> next() { return nextEntry(); }
1.413 - }
1.414 -
1.415 - // These Overrides alter the behavior of superclass view iterator() methods
1.416 - Iterator<K> newKeyIterator() { return new KeyIterator(); }
1.417 - Iterator<V> newValueIterator() { return new ValueIterator(); }
1.418 - Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); }
1.419 -
1.420 - /**
1.421 - * This override alters behavior of superclass put method. It causes newly
1.422 - * allocated entry to get inserted at the end of the linked list and
1.423 - * removes the eldest entry if appropriate.
1.424 - */
1.425 - void addEntry(int hash, K key, V value, int bucketIndex) {
1.426 - createEntry(hash, key, value, bucketIndex);
1.427 -
1.428 - // Remove eldest entry if instructed, else grow capacity if appropriate
1.429 - Entry<K,V> eldest = header.after;
1.430 - if (removeEldestEntry(eldest)) {
1.431 - removeEntryForKey(eldest.key);
1.432 - } else {
1.433 - if (size >= threshold)
1.434 - resize(2 * table.length);
1.435 - }
1.436 - }
1.437 -
1.438 - /**
1.439 - * This override differs from addEntry in that it doesn't resize the
1.440 - * table or remove the eldest entry.
1.441 - */
1.442 - void createEntry(int hash, K key, V value, int bucketIndex) {
1.443 - HashMap.Entry<K,V> old = table[bucketIndex];
1.444 - Entry<K,V> e = new Entry<>(hash, key, value, old);
1.445 - table[bucketIndex] = e;
1.446 - e.addBefore(header);
1.447 - size++;
1.448 - }
1.449 -
1.450 - /**
1.451 - * Returns <tt>true</tt> if this map should remove its eldest entry.
1.452 - * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
1.453 - * inserting a new entry into the map. It provides the implementor
1.454 - * with the opportunity to remove the eldest entry each time a new one
1.455 - * is added. This is useful if the map represents a cache: it allows
1.456 - * the map to reduce memory consumption by deleting stale entries.
1.457 - *
1.458 - * <p>Sample use: this override will allow the map to grow up to 100
1.459 - * entries and then delete the eldest entry each time a new entry is
1.460 - * added, maintaining a steady state of 100 entries.
1.461 - * <pre>
1.462 - * private static final int MAX_ENTRIES = 100;
1.463 - *
1.464 - * protected boolean removeEldestEntry(Map.Entry eldest) {
1.465 - * return size() > MAX_ENTRIES;
1.466 - * }
1.467 - * </pre>
1.468 - *
1.469 - * <p>This method typically does not modify the map in any way,
1.470 - * instead allowing the map to modify itself as directed by its
1.471 - * return value. It <i>is</i> permitted for this method to modify
1.472 - * the map directly, but if it does so, it <i>must</i> return
1.473 - * <tt>false</tt> (indicating that the map should not attempt any
1.474 - * further modification). The effects of returning <tt>true</tt>
1.475 - * after modifying the map from within this method are unspecified.
1.476 - *
1.477 - * <p>This implementation merely returns <tt>false</tt> (so that this
1.478 - * map acts like a normal map - the eldest element is never removed).
1.479 - *
1.480 - * @param eldest The least recently inserted entry in the map, or if
1.481 - * this is an access-ordered map, the least recently accessed
1.482 - * entry. This is the entry that will be removed it this
1.483 - * method returns <tt>true</tt>. If the map was empty prior
1.484 - * to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
1.485 - * in this invocation, this will be the entry that was just
1.486 - * inserted; in other words, if the map contains a single
1.487 - * entry, the eldest entry is also the newest.
1.488 - * @return <tt>true</tt> if the eldest entry should be removed
1.489 - * from the map; <tt>false</tt> if it should be retained.
1.490 - */
1.491 - protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
1.492 - return false;
1.493 - }
1.494 -}