/*
 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

//package java.util;
import java.util.*;

import java.io.Serializable;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.util.function.Consumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class HM<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

    private static final long serialVersionUID = 362498820763181265L;

    /*
     * Implementation notes. (in-progress.)
     *
     * This map usually acts as a binned (bucketed) hash table, but
     * when bins get too large, they are transformed into bins of
     * TreeNodes. Internal methods prefixed with "internal" try to use
     * normal bins, but relay to methods prefixed with "tree" when
     * applicable (simply by checking instanceof of a node).  Bins of
     * TreeNodes may be traversed and used like any other node, but
     * additionally support faster lookup when overpopulated. However,
     * since the vast majority of bins in normal use are not
     * overpopulated, checking for existence of treebins may be
     * delayed in the course of table methods. (Statistically, in
     * normal use with randomly distributed hashCodes, around 97% of
     * all bins have 2 or fewer nodes.)
     *
     * All "internal-" and "tree-" methods accept a hash code as an
     * argument (as normally supplied from a public methd), allowing
     * them to call each other without recomputing user hashCodes.
     * 
     * The root of a tree bin is normally its first node.  However,
     * sometimes (currently only upon Iterator.remove), the root might
     * be elsewhere, but can be recovered following parent links.
     *
     * The use and transitions among these is complicated by the
     * existence of LinkedHM. A number of hook methods are
     * defined to be invoked upon insertion, removal and access.  A
     * few are invoked only in LinkedHM methods, but most must
     * infiltrate table methods.
     *
     * Sorry if you don't like the concurrent-programming-like
     * SSA-based coding style. Among other things, it helps avoid
     * aliasing errors that otherwise lurk amid all the pointer
     * manipulations.
     */

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  The value reflects the approximate break-even point for
     * using tree-based operations.
     */
    static final int TREEBIN_THRESHOLD = 8;

    /**
     * The table. Initialized on first use, and resized as
     * necessary. Length MUST Always be a power of two.
     */
    transient Node<K,V>[] table;

    /**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     */
    transient Set<Map.Entry<K,V>> entrySet;
    transient Set<K> keySet; // fixme when not outside package
    transient Collection<V> values;

    /**
     * The number of key-value mappings contained in this map.
     */
    transient int size;

    /**
     * The number of times this HM has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HM or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HM fail-fast.  (See ConcurrentModificationException).
     */
    transient int modCount;

    /**
     * The next size value at which to resize (capacity * load factor).
     * @serial
     */
    int threshold; // holds initial capacity if table is unallocated

    /**
     * The load factor for the hash table.
     *
     * @serial
     */
    final float loadFactor;

    /**
     * Constructs an empty <tt>HM</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public HM(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

    /**
     * Constructs an empty <tt>HM</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HM(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Constructs an empty <tt>HM</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HM() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        this.threshold = DEFAULT_INITIAL_CAPACITY;
    }

    /**
     * Constructs a new <tt>HM</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HM</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public HM(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        this.threshold = DEFAULT_INITIAL_CAPACITY;
        internalPutAll(m);
    }

    /**
     * Returns the number of key-value mappings in this map.
     *
     * @return the number of key-value mappings in this map
     */
    public int size() {
        return size;
    }

    /**
     * Returns <tt>true</tt> if this map contains no key-value mappings.
     *
     * @return <tt>true</tt> if this map contains no key-value mappings
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        Node<K,V> e;
        return (e = internalGet((key == null) ? 0 : key.hashCode(), 
                                key)) == null ? null : e.value;
    }

    public V getOrDefault(Object key, V defaultValue) {
        Node<K,V> e;
        return (e = internalGet((key == null) ? 0 : key.hashCode(), 
                                key)) == null ? defaultValue : e.value;
    }

    /**
     * Returns <tt>true</tt> if this map contains a mapping for the
     * specified key.
     *
     * @param   key   The key whose presence in this map is to be tested
     * @return <tt>true</tt> if this map contains a mapping for the specified
     * key.
     */
    public boolean containsKey(Object key) {
        return internalGet((key == null) ? 0 : key.hashCode(), key) != null;
    }

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return internalPut((key == null) ? 0 : key.hashCode(), 
                           key, value, false);
    }

    /**
     * Copies all of the mappings from the specified map to this map.
     * These mappings will replace any mappings that this map had for
     * any of the keys currently in the specified map.
     *
     * @param m mappings to be stored in this map
     * @throws NullPointerException if the specified map is null
     */
    public void putAll(Map<? extends K, ? extends V> m) {
        internalPutAll(m);
    }

    /**
     * Implements Map.putAll and Map constructor
     */
    final void internalPutAll(Map<? extends K, ? extends V> m) {
        int s = m.size();
        if (s > 0) {
            if (table == null) {
                float ft = (s / loadFactor) + 1.0F;
                int t = (ft < MAXIMUM_CAPACITY) ? (int)ft : MAXIMUM_CAPACITY;
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            if (table == null || s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                internalPut((key == null) ? 0 : key.hashCode(), key, value, 
                            false);
            }
        }
    }

    /**
     * Removes the mapping for the specified key from this map if present.
     *
     * @param  key key whose mapping is to be removed from the map
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V remove(Object key) {
        Node<K,V> e;
        return (e = internalRemove((key == null) ? 0 : key.hashCode(), key, 
                                   null, false, true)) == null ? 
            null : e.value;
    }

    public V putIfAbsent(K key, V value) {
        return internalPut((key == null) ? 0 : key.hashCode(), key, 
                           value, true);
    }

    public boolean remove(Object key, Object value) {
        return internalRemove((key == null) ? 0 : key.hashCode(), key, 
                              value, true, true) != null;
    }

    public boolean replace(K key, V oldValue, V newValue) {
        Node<K,V> e; V v;
        if ((e = internalGet((key == null) ? 0 : key.hashCode(), key)) != null &&
            ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
            e.value = newValue;
            return true;
        }
        return false;
    }

    public V replace(K key, V value) {
        Node<K,V> e;
        if ((e = internalGet((key == null) ? 0 : key.hashCode(), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            return oldValue;
        }
        return null;
    }

    public V computeIfAbsent(K key, 
                             Function<? super K, ? extends V> mappingFunction) {
        if (mappingFunction == null)
            throw new NullPointerException();
        int hash = (key == null) ? 0 : key.hashCode();
        Node<K,V>[] tab; Node<K,V> first; int i; 
        int binCount = 0;
        boolean treeBin = false;
        if ((tab = table) == null || size >= threshold)
            tab = resize();
        if ((first = tab[i = (tab.length - 1) & hash]) != null) {
            Node<K,V> old = null;
            if (first instanceof TreeNode) {
                treeBin = true;
                old = treeGet(((TreeNode<K,V>)first).root(), hash, key, null);
            }
            else {
                Node<K,V> e = first;
                do {
                    K k;
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
            if (old != null) {
                V v = old.value;
                if (v == null) 
                    old.value = v = mappingFunction.apply(key);
                return v;
            }
        }
        V v = mappingFunction.apply(key);
        if (v == null)
            return null;
        if (treeBin)
            treePut(tab, (TreeNode<K,V>)first, hash, key, v);
        else {
            tab[i] = new Node<K,V>(hash, key, v, first);
            if (binCount >= TREEBIN_THRESHOLD)
                convertToTreeNodes(tab, i);
        }
        ++modCount;
        ++size;
        return v;
    }

    public V computeIfPresent(K key, 
                              BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        return recomputeValue(key, true, remappingFunction);
    }

    public V compute(K key, 
                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        return recomputeValue(key, false, remappingFunction);
    }

    V recomputeValue(K key, boolean onlyIfPresent,
                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        if (remappingFunction == null)
            throw new NullPointerException();
        int hash = (key == null) ? 0 : key.hashCode();
        Node<K,V>[] tab; Node<K,V> first; int i; V v;
        int binCount = 0;
        boolean treeBin = false;
        if ((tab = table) == null || size >= threshold)
            tab = resize();
        if ((first = tab[i = (tab.length - 1) & hash]) != null) {
            Node<K,V> old = null;
            if (first instanceof TreeNode) {
                treeBin = true;
                old = treeGet(((TreeNode<K,V>)first).root(), hash, key, null);
            }
            else {
                Node<K,V> e = first;
                do {
                    K k;
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
            if (old != null) {
                V oldValue = old.value;
                if (oldValue == null && onlyIfPresent)
                    v = null; // odd but forced by spec
                else if ((v = remappingFunction.apply(key, oldValue)) != null) {
                    old.value = v;
                }
                else
                    internalRemove(hash, key, null, false, true);
                return v;
            }
        }
        if (onlyIfPresent || (v = remappingFunction.apply(key, null)) == null)
            return null;
        if (treeBin)
            treePut(tab, (TreeNode<K,V>)first, hash, key, v);
        else {
            tab[i] = new Node<K,V>(hash, key, v, first);
            if (binCount >= TREEBIN_THRESHOLD)
                convertToTreeNodes(tab, i);
        }
        ++modCount;
        ++size;
        return v;
    }

    public V merge(K key, V value, 
                   BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        if (remappingFunction == null)
            throw new NullPointerException();
        int hash = (key == null) ? 0 : key.hashCode();
        Node<K,V>[] tab; Node<K,V> first; int i;
        int binCount = 0;
        boolean treeBin = false;
        if ((tab = table) == null || size >= threshold)
            tab = resize();
        if ((first = tab[i = (tab.length - 1) & hash]) != null) {
            Node<K,V> old = null;
            if (first instanceof TreeNode) {
                treeBin = true;
                old = treeGet(((TreeNode<K,V>)first).root(), hash, key, null);
            }
            else {
                Node<K,V> e = first;
                do {
                    K k;
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
            if (old != null) {
                V v = remappingFunction.apply(old.value, value);
                if (v != null) {
                    old.value = v;
                }
                else
                    internalRemove(hash, key, null, false, true);
                return v;
            }
        }
        if (value != null) {
            if (treeBin)
                treePut(tab, (TreeNode<K,V>)first, hash, key, value);
            else {
                tab[i] = new Node<K,V>(hash, key, value, first);
                if (binCount >= TREEBIN_THRESHOLD)
                    convertToTreeNodes(tab, i);
            }
            ++modCount;
            ++size;
        }
        return value;
    }

    /**
     * Removes all of the mappings from this map.
     * The map will be empty after this call returns.
     */
    public void clear() {
        modCount++;
        if (size > 0) {
            size = 0;
            Node<K,V>[] tab = table;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }

    /**
     * Returns <tt>true</tt> if this map maps one or more keys to the
     * specified value.
     *
     * @param value value whose presence in this map is to be tested
     * @return <tt>true</tt> if this map maps one or more keys to the
     *         specified value
     */
    public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
        if ((tab = table) != null) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                        (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }

    /**
     * Returns a shallow copy of this <tt>HM</tt> instance: the keys and
     * values themselves are not cloned.
     *
     * @return a shallow copy of this map
     */
    @SuppressWarnings("unchecked")
    public Object clone() {
        HM<K,V> result = null;
        try {
            result = (HM<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            // assert false;
        }
        result.reinitialize();
        result.threshold = DEFAULT_INITIAL_CAPACITY;
        result.internalPutAll(this);
        return result;
    }

    /**
     * Returns a {@link Set} view of the keys contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own <tt>remove</tt> operation), the results of
     * the iteration are undefined.  The set supports element removal,
     * which removes the corresponding mapping from the map, via the
     * <tt>Iterator.remove</tt>, <tt>Set.remove</tt>,
     * <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt>
     * operations.  It does not support the <tt>add</tt> or <tt>addAll</tt>
     * operations.
     */
    public Set<K> keySet() {
        Set<K> ks = keySet;
        return (ks != null ? ks : (keySet = new KeySet()));
    }

    /**
     * Returns a {@link Collection} view of the values contained in this map.
     * The collection is backed by the map, so changes to the map are
     * reflected in the collection, and vice-versa.  If the map is
     * modified while an iteration over the collection is in progress
     * (except through the iterator's own <tt>remove</tt> operation),
     * the results of the iteration are undefined.  The collection
     * supports element removal, which removes the corresponding
     * mapping from the map, via the <tt>Iterator.remove</tt>,
     * <tt>Collection.remove</tt>, <tt>removeAll</tt>,
     * <tt>retainAll</tt> and <tt>clear</tt> operations.  It does not
     * support the <tt>add</tt> or <tt>addAll</tt> operations.
     */
    public Collection<V> values() {
        Collection<V> vs = values;
        return (vs != null ? vs : (values = new Values()));
    }

    /**
     * Returns a {@link Set} view of the mappings contained in this map.
     * The set is backed by the map, so changes to the map are
     * reflected in the set, and vice-versa.  If the map is modified
     * while an iteration over the set is in progress (except through
     * the iterator's own <tt>remove</tt> operation, or through the
     * <tt>setValue</tt> operation on a map entry returned by the
     * iterator) the results of the iteration are undefined.  The set
     * supports element removal, which removes the corresponding
     * mapping from the map, via the <tt>Iterator.remove</tt>,
     * <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
     * <tt>clear</tt> operations.  It does not support the
     * <tt>add</tt> or <tt>addAll</tt> operations.
     *
     * @return a set view of the mappings contained in this map
     */
    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es = entrySet;
        return es != null ? es : (entrySet = new EntrySet());
    }

    /**
     * Save the state of the <tt>HM</tt> instance to a stream (i.e.,
     * serialize it).
     *
     * @serialData The <i>capacity</i> of the HM (the length of the
     *             bucket array) is emitted (int), followed by the
     *             <i>size</i> (an int, the number of key-value
     *             mappings), followed by the key (Object) and value (Object)
     *             for each key-value mapping.  The key-value mappings are
     *             emitted in no particular order.
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws IOException {
        int b = (table == null) ? threshold : table.length;
        // Write out the threshold, loadfactor, and any hidden stuff
        s.defaultWriteObject();
        s.writeInt(b);        // Write out number of buckets
        s.writeInt(size);     // Write out size (number of Mappings)
        if (size > 0) {       // Write out keys and values (alternating)
            for(Map.Entry<K,V> e : new EntrySet()) {
                s.writeObject(e.getKey());
                s.writeObject(e.getValue());
            }
        }
    }

    /**
     * Reconstitute the {@code HM} instance from a stream (i.e.,
     * deserialize it).
     */
    private void readObject(java.io.ObjectInputStream s)
        throws IOException, ClassNotFoundException {
        // Read in the threshold (ignored), loadfactor, and any hidden stuff
        s.defaultReadObject();
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new InvalidObjectException("Illegal load factor: " +
                                             loadFactor);
        s.readInt();                // Read and ignore number of buckets
        int mappings = s.readInt(); // Read number of mappings (size)
        if (mappings < 0)
            throw new InvalidObjectException("Illegal mappings count: " +
                                             mappings);
        // Compute capacity by number of mappings and desired load (if >= 0.25)
        int capacity = tableSizeFor((int)Math.min(mappings * 
                                                  Math.min(1 / loadFactor, 4.0f),
                                                  MAXIMUM_CAPACITY));
        reinitialize();
        threshold = capacity;
        // Read the keys and values, and put the mappings in the HM
        for (int i = 0; i < mappings; i++) {
            @SuppressWarnings("unchecked")
                K key = (K) s.readObject();
            @SuppressWarnings("unchecked")
                V value = (V) s.readObject();
            internalPut((key == null) ? 0 : key.hashCode(), key, value, 
                        false);
        }
    }

    // These methods are used when serializing HashSets
    int capacity()      { return (table == null) ?  threshold : table.length; }
    float loadFactor()  { return loadFactor;   }

    /* ------------------------------------------------------------ */
    // Node classes

    /**
     * Basic hash bin node, used for most entries.
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

    static final class TreeNode<K,V> extends Node<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val) {
            super(hash, key, val, null);
        }
        final TreeNode<K,V> root() {
            TreeNode<K,V> r = this, p;
            while ((p = r.parent) != null)
                r = p;
            return r;
        }
    }

    /* ------------------------------------------------------------ */
    // hooks for LinkedHM

    final void reinitialize() {
        table = null;
        entrySet = null;
        keySet = null;
        values = null;
        modCount = 0;
        size = 0;
    }

    // for conversion from TreeNodes to plain nodes
    final Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
        return new Node<K,V>(p.hash, p.key, p.value, next);
    }

    // for convertToTreeNodes
    final TreeNode<K,V> replacementTreeNode(Node<K,V> p) {
        return new TreeNode<K,V>(p.hash, p.key, p.value);
    }

    /* ------------------------------------------------------------ */
    // table construction and maintenance 

    private static int tableSizeFor(int number) {
        int n = number - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     */
    @SuppressWarnings({"rawtypes","unchecked"})
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab, newTab;
        int n = ((oldTab = table) == null) ? 0 : oldTab.length;
        if (n >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        int cap = (n == 0) ? threshold : n << 1;
        float ft = cap * loadFactor;
        threshold = (cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY ?
                     (int)ft : Integer.MAX_VALUE);
        table = newTab = (Node<K,V>[])new Node[cap];
        if (oldTab != null) {
            int mask = cap - 1;
            for (int j = 0; j < n; ++j) {
                Node<K,V> e, next;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e instanceof TreeNode) 
                        splitTreeBin((TreeNode<K,V>)e, newTab, j, n);
                    else {
                        do {
                            int i = e.hash & mask;
                            next = e.next;
                            e.next = newTab[i];
                            newTab[i] = e;
                        } while ((e = next) != null);
                    }
                }
            }
        }
        return newTab;
    }

    /* ------------------------------------------------------------ */
    // primary get, put, remove methods 

    /**
     * Implements Map.get and related methods
     */
    final Node<K,V> internalGet(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int i; K k; TreeNode<K,V> r;
        if ((tab = table) != null && (i = (tab.length - 1) & hash) >= 0 &&
            (first = tab[i]) != null) {
            if (first.hash == hash &&
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return treeGet((r = (TreeNode<K,V>)first).parent != null ?
                                   r.root() : r, hash, key, null);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
    static <K,V> TreeNode<K,V> treeGet(TreeNode<K,V> p, int hash, Object key,
                                           Class<?> cc) {
        while (p != null) {
            int ph, dir; Object pk; Class<?> pc;  TreeNode<K,V> q;
            TreeNode<K,V> pl = p.left, pr = p.right;
            if ((ph = p.hash) > hash)
                p = pl;
            else if (ph < hash)
                p = pr;
            else if ((pk = p.key) == key || (key != null && key.equals(pk)))
                return p;
            else if (pl == null && pr == null)
                break;
            else if (pk != null && (key instanceof Comparable) && 
                     (cc != null ||
                      (cc = comparableClassFor(key.getClass())) != null) &&
                     ((pc = pk.getClass()) == cc ||
                      comparableClassFor(pc) == cc) &&
                     (dir = ((Comparable)key).compareTo(pk)) != 0)
                p = (dir < 0) ? pl : pr;
            else if (pr == null)
                p = pl;
            else if (pl == null)
                p = pr;
            else if ((q = treeGet(pr, hash, key, cc)) == null)
                p = pl;
            else
                return q;
        }
        return null;
    }

    /**
     * Implements Map.put and related methods
     */
    final V internalPut(int hash, K key, V value, boolean onlyIfAbsent) {
        Node<K,V>[] tab; Node<K,V> first; int i;
        int binCount = 0;
        boolean treeBin = false;
        if ((tab = table) == null || size >= threshold)
            tab = resize();
        if ((first = tab[i = (tab.length - 1) & hash]) != null) {
            Node<K,V> e; K k;
            if (first instanceof TreeNode) {
                treeBin = true;
                e = treePut(tab, (TreeNode<K,V>)first, hash, key, value);
            }
            else {
                e = first;
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    ++binCount;
                } while ((e = e.next) != null);
            }
            if (e != null) {
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                return oldValue;
            }
        }
        if (!treeBin) {
            tab[i] = new Node<K,V>(hash, key, value, first);
            if (binCount >= TREEBIN_THRESHOLD)
                convertToTreeNodes(tab, i);
        }
        ++modCount;
        ++size;
        return null;
    }

    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
    final TreeNode<K,V> treePut(Node<K,V>[] tab, TreeNode<K,V> first, int hash,
                                K key, V value) {
        Class<?> cc = null;
        TreeNode<K,V> root = (first.parent != null) ? first.root() : first;
        for (TreeNode<K,V> p = root;;) {
            int dir, ph; Object pk; Class<?> pc; TreeNode<K,V> q, pr;
            if ((ph = p.hash) > hash)
                dir = -1;
            else if (ph < hash)
                dir = 1;
            else if ((pk = p.key) == key || (key != null && key.equals(pk)))
                return p;
            else {
                if (pk != null && (key instanceof Comparable) && 
                    (cc != null ||
                     (cc = comparableClassFor(key.getClass())) != null) &&
                    ((pc = pk.getClass()) == cc ||
                     comparableClassFor(pc) == cc))
                    dir = ((Comparable)key).compareTo(pk);
                else
                    dir = 0;
                if (dir == 0) {
                    if ((pr = p.right) == null)
                        dir = -1;
                    else if (p.left == null)
                        dir = 1;
                    else if ((q = treeGet(pr, hash, key, cc)) != null)
                        return q;
                }
            }
            TreeNode<K,V> parent = p;
            if ((p = (dir <= 0) ? p.left : p.right) == null) {
                TreeNode<K,V> x = new TreeNode<K,V>(hash, key, value);
                x.parent = parent;
                if (dir <= 0)
                    parent.left = x;
                else
                    parent.right = x;
                moveRootToFront(tab, balanceInsertion(root, x), x);
                return null;
            }
        }
    }

    /**
     * Implements Map.remove and related methods
     */
    final Node<K,V> internalRemove(int hash, Object key, Object value,
                                   boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> e; int i;
        if ((tab = table) != null && (i = (tab.length - 1) & hash) >= 0 &&
            (e = tab[i]) != null) {
            Node<K,V> result = null;
            if (e instanceof TreeNode) {
                TreeNode<K,V> r, p; V v;
                if ((p = treeGet((r = (TreeNode<K,V>)e).parent != null ?
                                 r.root() : r, hash, key, null)) != null &&
                    (!matchValue || (v = p.value) == value ||
                     (value != null && value.equals(v)))) {
                    result = p;
                    treeRemove(tab, p, movable);
                }
            }
            else {
                for (Node<K,V> pred = null;;) {
                    K k; V v;
                    Node<K,V> next = e.next;
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        if (!matchValue || (v = e.value) == value ||
                            (value != null && value.equals(v))) {
                            if (pred == null)
                                tab[i] = next;
                            else
                                pred.next = next;
                            result = e;
                            break;
                        }
                        break;
                    }
                    pred = e;
                    if ((e = next) == null)
                        break;
                }
            }
            if (result != null) {
                ++modCount;
                --size;
                return result;
            }
        }
        return null;
    }

    /**
     * Removes the given node, that must be present before this call.
     * This is messier than typical red-black deletion code because we
     * cannot swap the contents of an interior node with a leaf
     * successor that is pinned by "next" pointers that are accessible
     * independently during traversal. So instead we swap the tree
     * linkages.
     */
    final void treeRemove(Node<K,V>[] tab, TreeNode<K,V> p, boolean movable) {
        int index = (tab.length - 1) & p.hash;
        TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
        TreeNode<K,V> next = (TreeNode<K,V>)p.next;
        TreeNode<K,V> pred = p.prev;
        if (pred == null)
            first = (TreeNode<K,V>)(tab[index] = next);
        else
            pred.next = next;
        if (next != null)
            next.prev = pred;
        if (first == null)
            return;
        if (first.next == null) { // untreeify if only one element remains
            if (movable)
                tab[index] = replacementNode(first, null);
            else {
                first.parent = first.left = first.right = first.prev = null;
                first.red = false;
            }
            return;
        }
        TreeNode<K,V> root = first.root();
        TreeNode<K,V> replacement;
        TreeNode<K,V> pl = p.left, pr = p.right;
        if (pl != null && pr != null) {
            TreeNode<K,V> s = pr, sl;
            while ((sl = s.left) != null) // find successor
                s = sl;
            boolean c = s.red; s.red = p.red; p.red = c; // swap colors
            TreeNode<K,V> sr = s.right;
            TreeNode<K,V> pp = p.parent;
            if (s == pr) { // p was s's direct parent
                p.parent = s;
                s.right = p;
            }
            else {
                TreeNode<K,V> sp = s.parent;
                if ((p.parent = sp) != null) {
                    if (s == sp.left)
                        sp.left = p;
                    else
                        sp.right = p;
                }
                if ((s.right = pr) != null)
                    pr.parent = s;
            }
            p.left = null;
            if ((p.right = sr) != null)
                sr.parent = p;
            if ((s.left = pl) != null)
                pl.parent = s;
            if ((s.parent = pp) == null)
                root = s;
            else if (p == pp.left)
                pp.left = s;
            else
                pp.right = s;
            if (sr != null)
                replacement = sr;
            else
                replacement = p;
        }
        else if (pl != null)
            replacement = pl;
        else if (pr != null)
            replacement = pr;
        else
            replacement = p;
        if (replacement != p) {
            TreeNode<K,V> pp = replacement.parent = p.parent;
            if (pp == null)
                root = replacement;
            else if (p == pp.left)
                pp.left = replacement;
            else
                pp.right = replacement;
            p.left = p.right = p.parent = null;
        }

        TreeNode<K,V> r = (p.red) ? root : balanceDeletion(root, replacement);

        if (replacement == p) {  // detach
            TreeNode<K,V> pp = p.parent;
            p.parent = null;
            if (pp != null) {
                if (p == pp.left)
                    pp.left = null;
                else if (p == pp.right)
                    pp.right = null;
            }
        }
        if (movable)
            moveRootToFront(tab, r, null);
    }

    /* ------------------------------------------------------------ */
    // Tree utilities

    /**
     * Returns a Class for the given type of the form "class C
     * implements Comparable<C>", if one exists, else null.
     */
    static Class<?> comparableClassFor(Class<?> c) {
        Class<?> s, cmpc; Type[] ts, as; Type t; ParameterizedType p;
        if (c == String.class) // bypass checks
            return c;
        if (c != null && (cmpc = Comparable.class).isAssignableFrom(c)) {
            while (cmpc.isAssignableFrom(s = c.getSuperclass()))
                c = s; // find topmost comparable class
            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() == cmpc) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }

    /**
     * Replaces all linked nodes at given index with TreeNodes
     */
    final void convertToTreeNodes(Node<K,V>[] tab, int index) {
        TreeNode<K,V> b = null;
        for (Node<K,V> e = tab[index]; e != null; e = e.next) {
            TreeNode<K,V> p = replacementTreeNode(e);
            if ((p.next = b) != null)
                b.prev = p;
            b = p;
        }
        tab[index] = b;
        moveRootToFront(tab, treeify(b), null);
    }

    /**
     * Forms tree of the nodes linked from node b
     */
    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
    static <K,V> TreeNode<K,V> treeify(TreeNode<K,V> b) {
        TreeNode<K,V> root = null, next;
        for (TreeNode<K,V> x = b; x != null; x = next) {
            next = (TreeNode<K,V>)x.next;
            if (root == null) 
                (root = x).red = false;
            else {
                Class<?> cc = null;
                K key = x.key;
                int hash = x.hash;
                for (TreeNode<K,V> p = root;;) {
                    int dir, ph; Object pk; Class<?> pc;
                    if ((ph = p.hash) > hash)
                        dir = -1;
                    else if (ph < hash)
                        dir = 1;
                    else if ((pk = p.key) != null && 
                             (key instanceof Comparable) && 
                             (cc != null ||
                              (cc = comparableClassFor(key.getClass())) != null) &&
                             ((pc = pk.getClass()) == cc ||
                              comparableClassFor(pc) == cc))
                        dir = ((Comparable)key).compareTo(pk);
                    else
                        dir = 0;
                    TreeNode<K,V> parent = p;
                    if ((p = (dir <= 0) ? p.left : p.right) == null) {
                        x.parent = parent;
                        if (dir <= 0)
                            parent.left = x;
                        else
                            parent.right = x;
                        root = balanceInsertion(root, x);
                        break;
                    }
                }
            }
        }
        return root;
    }


    final void splitTreeBin(TreeNode<K,V> b, Node<K,V>[] tab, 
                            int index, int bit) {
        TreeNode<K,V> lb = null, hb = null, next;
        int lc = 0, hc = 0;
        for (TreeNode<K,V> e = b; e != null; e = next) {
            next = (TreeNode<K,V>)e.next;
            e.parent = e.left = e.right = e.prev = null;
            if ((e.hash & bit) == 0) {
                if ((e.next = lb) != null)
                    lb.prev = e;
                lb = e;
                ++lc;
            }
            else {
                if ((e.next = hb) != null)
                    hb.prev = e;
                hb = e;
                ++hc;
            }
        }
        if (lc > TREEBIN_THRESHOLD >>> 1) {
            tab[index] = lb;
            moveRootToFront(tab, treeify(lb), null);
        }
        else if (lb != null) {
            Node<K,V> q = null;
            for (Node<K,V> p = lb; p != null; p = p.next)
                q = replacementNode(p, q);
            tab[index] = q;
        }
        if (hc > TREEBIN_THRESHOLD >>> 1) {
            tab[index + bit] = hb;
            moveRootToFront(tab, treeify(hb), null);
        }
        else if (hb != null) {
            Node<K,V> q = null;
            for (Node<K,V> p = hb; p != null; p = p.next)
                q = replacementNode(p, q);
            tab[index + bit] = q;
        }
    }        

    /**
     * Ensures that the given root is first node in its bin, and also
     * attaches the given added node (or null if not added), which may
     * be the same as root node.
     */
    static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root,
                                      TreeNode<K,V> added) {
        int index = root.hash & (tab.length - 1);
        TreeNode<K,V> first = (TreeNode<K,V>)tab[index];
        if (first == null) {
            tab[index] = root;
            root.next = null;
            root.prev = null;
        }
        else if (root == added) {
            tab[index] = root;
            first.prev = root;
            root.next = first;
            root.prev = null;
        }
        else if (root != first) {
            tab[index] = root;
            TreeNode<K,V> rn = (TreeNode<K,V>)root.next;
            TreeNode<K,V> rp = root.prev;
            if (rn != null) 
                rn.prev = rp;
            if (rp != null) 
                rp.next = rn;
            if (added != null) {
                TreeNode<K,V> fn = (TreeNode<K,V>)first.next;
                if ((added.next = fn) != null)
                    fn.prev = added;
                added.prev = first;
                first.next = added;
            }
            first.prev = root;
            root.next = first;
            root.prev = null;
        }
        else if (added != null) {
            TreeNode<K,V> rn = (TreeNode<K,V>)root.next;
            if ((added.next = rn) != null) 
                rn.prev = added;
            added.prev = root;
            root.next = added;
        }

        assert checkTreeNode(root);
    }

    /* ------------------------------------------------------------ */
    // iterators 

    abstract class HashIterator {
        Node<K,V> next;        // next entry to return
        Node<K,V> current;     // current entry
        int expectedModCount;  // for fast-fail
        int index;             // current slot

        HashIterator() {
            Node<K,V>[] t = table;
            expectedModCount = modCount;
            index = 0;
            if (t != null && size > 0) { // advance to first entry
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            current = e;
            if ((next = e.next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

        public final void remove() {
            Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            K key = p.key;
            internalRemove((key == null) ? 0 : key.hashCode(), key, 
                           null, false, false);
            current = null;
            expectedModCount = modCount;
        }

    }

    final class KeyIterator extends HashIterator
        implements Iterator<K> {
        public final K next() { return nextNode().key; }
    }

    final class ValueIterator extends HashIterator
        implements Iterator<V> {
        public final V next() { return nextNode().value; }
    }

    final class EntryIterator extends HashIterator
        implements Iterator<Map.Entry<K,V>> {
        public final Map.Entry<K,V> next() { return nextNode(); }
    }

    /* ------------------------------------------------------------ */
    // spliterators

    static class HMSpliterator<K,V> {
        final HM<K,V> map;
        HM.Node<K,V> current;  // current node
        int index;                  // current index, modified on advance/split
        int fence;                  // one past last index
        int est;                    // size estimate
        int expectedModCount;       // for comodification checks

        HMSpliterator(HM<K,V> m, int origin,
                           int fence, int est,
                           int expectedModCount) {
            this.map = m;
            this.index = origin;
            this.fence = fence;
            this.est = est;
            this.expectedModCount = expectedModCount;
        }

        final int getFence() { // initialize fence and size on first use
            int hi;
            if ((hi = fence) < 0) {
                HM<K,V> m = map;
                est = m.size;
                expectedModCount = m.modCount;
                HM.Node<K,V>[] tab = m.table;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            return hi;
        }

        public final long estimateSize() {
            getFence(); // force init
            return (long) est;
        }
    }

    static final class KeySpliterator<K,V>
        extends HMSpliterator<K,V>
        implements Spliterator<K> {
        KeySpliterator(HM<K,V> m, int origin, int fence, int est,
                       int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public KeySpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                new KeySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
                                        expectedModCount);
        }

        public void forEachRemaining(Consumer<? super K> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HM<K,V> m = map;
            HM.Node<K,V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            else
                mc = expectedModCount;
            if (tab != null && tab.length >= hi &&
                (i = index) >= 0 && (i < (index = hi) || current != null)) {
                HM.Node<K,V> p = current;
                current = null;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p.key);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        public boolean tryAdvance(Consumer<? super K> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            HM.Node<K,V>[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        K k = current.key;
                        current = current.next;
                        action.accept(k);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                Spliterator.DISTINCT;
        }
    }

    static final class ValueSpliterator<K,V>
        extends HMSpliterator<K,V>
        implements Spliterator<V> {
        ValueSpliterator(HM<K,V> m, int origin, int fence, int est,
                         int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public ValueSpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                new ValueSpliterator<K,V>(map, lo, index = mid, est >>>= 1,
                                          expectedModCount);
        }

        public void forEachRemaining(Consumer<? super V> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HM<K,V> m = map;
            HM.Node<K,V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            else
                mc = expectedModCount;
            if (tab != null && tab.length >= hi &&
                (i = index) >= 0 && (i < (index = hi) || current != null)) {
                HM.Node<K,V> p = current;
                current = null;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p.value);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        public boolean tryAdvance(Consumer<? super V> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            HM.Node<K,V>[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        V v = current.value;
                        current = current.next;
                        action.accept(v);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0);
        }
    }

    static final class EntrySpliterator<K,V>
        extends HMSpliterator<K,V>
        implements Spliterator<Map.Entry<K,V>> {
        EntrySpliterator(HM<K,V> m, int origin, int fence, int est,
                         int expectedModCount) {
            super(m, origin, fence, est, expectedModCount);
        }

        public EntrySpliterator<K,V> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid || current != null) ? null :
                new EntrySpliterator<K,V>(map, lo, index = mid, est >>>= 1,
                                          expectedModCount);
        }

        public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
            int i, hi, mc;
            if (action == null)
                throw new NullPointerException();
            HM<K,V> m = map;
            HM.Node<K,V>[] tab = m.table;
            if ((hi = fence) < 0) {
                mc = expectedModCount = m.modCount;
                hi = fence = (tab == null) ? 0 : tab.length;
            }
            else
                mc = expectedModCount;
            if (tab != null && tab.length >= hi &&
                (i = index) >= 0 && (i < (index = hi) || current != null)) {
                HM.Node<K,V> p = current;
                current = null;
                do {
                    if (p == null)
                        p = tab[i++];
                    else {
                        action.accept(p);
                        p = p.next;
                    }
                } while (p != null || i < hi);
                if (m.modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }

        public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
            int hi;
            if (action == null)
                throw new NullPointerException();
            HM.Node<K,V>[] tab = map.table;
            if (tab != null && tab.length >= (hi = getFence()) && index >= 0) {
                while (current != null || index < hi) {
                    if (current == null)
                        current = tab[index++];
                    else {
                        HM.Node<K,V> e = current;
                        current = current.next;
                        action.accept(e);
                        if (map.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                }
            }
            return false;
        }

        public int characteristics() {
            return (fence < 0 || est == map.size ? Spliterator.SIZED : 0) |
                Spliterator.DISTINCT;
        }
    }

    /* ------------------------------------------------------------ */
    // Views

    final class KeySet extends AbstractSet<K> {
        public int size()                 { return size; }
        public void clear()               { HM.this.clear(); }
        public Iterator<K> iterator()     { return new KeyIterator(); }
        public boolean contains(Object o) { return containsKey(o); }
        public boolean remove(Object key) {
            return internalRemove((key == null) ? 0 : key.hashCode(), key, 
                                  null, false, true) != null;
        }
        public Spliterator<K> spliterator() {
            return new KeySpliterator<K,V>(HM.this, 0, -1, 0, 0);
        }
        public void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if ((tab = table) != null) {
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
            }
        }
    }

    final class Values extends AbstractCollection<V> {
        public int size()                 { return size; }
        public void clear()               { HM.this.clear(); }
        public Iterator<V> iterator()     { return new ValueIterator(); }
        public boolean contains(Object o) { return containsValue(o); }
        public Spliterator<V> spliterator() {
            return new ValueSpliterator<K,V>(HM.this, 0, -1, 0, 0);
        }
        public void forEach(Consumer<? super V> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if ((tab = table) != null) {
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.value);
                }
            }
        }
    }

    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public int size()                 { return size; }
        public void clear()               { HM.this.clear(); }
        public Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
        public boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
            Object key = e.getKey();
            Node<K,V> candidate = internalGet((key == null) ? 0 : key.hashCode(),
                                              key);
            return candidate != null && candidate.equals(e);
        }
        public boolean remove(Object o) {
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>) o;
                Object key = e.getKey();
                Object value = e.getValue();
                return internalRemove((key == null) ? 0 : key.hashCode(), 
                                      key, value, true, true) != null;
            }
            return false;
        }
        public Spliterator<Map.Entry<K,V>> spliterator() {
            return new EntrySpliterator<K,V>(HM.this, 0, -1, 0, 0);
        }
        public void forEach(Consumer<? super Map.Entry<K,V>> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if ((tab = table) != null) {
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
            }
        }
    }

    /* ------------------------------------------------------------ */
    // Red-black tree methods, all adapted from CLR

    static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root, TreeNode<K,V> p) {
        if (p != null) {
            TreeNode<K,V> r = p.right, pp, rl;
            if ((rl = p.right = r.left) != null)
                rl.parent = p;
            if ((pp = r.parent = p.parent) == null)
                (root = r).red = false;
            else if (pp.left == p)
                pp.left = r;
            else
                pp.right = r;
            r.left = p;
            p.parent = r;
        }
        return root;
    }

    static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root, TreeNode<K,V> p) {
        if (p != null) {
            TreeNode<K,V> l = p.left, pp, lr;
            if ((lr = p.left = l.right) != null)
                lr.parent = p;
            if ((pp = l.parent = p.parent) == null)
                (root = l).red = false;
            else if (pp.right == p)
                pp.right = l;
            else
                pp.left = l;
            l.right = p;
            p.parent = l;
        }
        return root;
    }

    static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                TreeNode<K,V> x) {
        x.red = true;
        for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
            if ((xp = x.parent) == null) {
                x.red = false;
                return x;
            }
            else if (!xp.red || (xpp = xp.parent) == null)
                return root;
            if (xp == (xppl = xpp.left)) {
                if ((xppr = xpp.right) != null && xppr.red) {
                    xppr.red = false;
                    xp.red = false;
                    xpp.red = true;
                    x = xpp;
                }
                else {
                    if (x == xp.right) {
                        root = rotateLeft(root, x = xp);
                        xpp = (xp = x.parent) == null ? null : xp.parent;
                    }
                    if (xp != null) {
                        xp.red = false;
                        if (xpp != null) {
                            xpp.red = true;
                            root = rotateRight(root, xpp);
                        }
                    }
                }
            }
            else {
                if (xppl != null && xppl.red) {
                    xppl.red = false;
                    xp.red = false;
                    xpp.red = true;
                    x = xpp;
                }
                else {
                    if (x == xp.left) {
                        root = rotateRight(root, x = xp);
                        xpp = (xp = x.parent) == null ? null : xp.parent;
                    }
                    if (xp != null) {
                        xp.red = false;
                        if (xpp != null) {
                            xpp.red = true;
                            root = rotateLeft(root, xpp);
                        }
                    }
                }
            }
        }
    }

    static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
                                               TreeNode<K,V> x) {
        for (TreeNode<K,V> xp, xpl, xpr;;)  {
            if (x == null || x == root)
                return root;
            else if ((xp = x.parent) == null) {
                x.red = false;
                return x;
            }
            else if (x.red) {
                x.red = false;
                return root;
            }
            else if ((xpl = xp.left) == x) {
                if ((xpr = xp.right) != null && xpr.red) {
                    xpr.red = false;
                    xp.red = true;
                    root = rotateLeft(root, xp);
                    xpr = (xp = x.parent) == null ? null : xp.right;
                }
                if (xpr == null)
                    x = xp;
                else {
                    TreeNode<K,V> sl = xpr.left, sr = xpr.right;
                    if ((sr == null || !sr.red) &&
                        (sl == null || !sl.red)) {
                        xpr.red = true;
                        x = xp;
                    }
                    else {
                        if (sr == null || !sr.red) {
                            if (sl != null)
                                sl.red = false;
                            xpr.red = true;
                            root = rotateRight(root, xpr);
                            xpr = (xp = x.parent) == null ?
                                null : xp.right;
                        }
                        if (xpr != null) {
                            xpr.red = (xp == null) ? false : xp.red;
                            if ((sr = xpr.right) != null)
                                sr.red = false;
                        }
                        if (xp != null) {
                            xp.red = false;
                            root = rotateLeft(root, xp);
                        }
                        x = root;
                    }
                }
            }
            else { // symmetric
                if (xpl != null && xpl.red) {
                    xpl.red = false;
                    xp.red = true;
                    root = rotateRight(root, xp);
                    xpl = (xp = x.parent) == null ? null : xp.left;
                }
                if (xpl == null)
                    x = xp;
                else {
                    TreeNode<K,V> sl = xpl.left, sr = xpl.right;
                    if ((sl == null || !sl.red) &&
                        (sr == null || !sr.red)) {
                        xpl.red = true;
                        x = xp;
                    }
                    else {
                        if (sl == null || !sl.red) {
                            if (sr != null)
                                sr.red = false;
                            xpl.red = true;
                            root = rotateLeft(root, xpl);
                            xpl = (xp = x.parent) == null ?
                                null : xp.left;
                        }
                        if (xpl != null) {
                            xpl.red = (xp == null) ? false : xp.red;
                            if ((sl = xpl.left) != null)
                                sl.red = false;
                        }
                        if (xp != null) {
                            xp.red = false;
                            root = rotateRight(root, xp);
                        }
                        x = root;
                    }
                }
            }
        }
    }

    /**
     * Recursive invariant check
     */
    static <K,V> boolean checkTreeNode(TreeNode<K,V> t) {
        TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
            tb = t.prev, tn = (TreeNode<K,V>)t.next;
        if (tb != null && tb.next != t)
            return false;
        if (tn != null && tn.prev != t)
            return false;
        if (tp != null && t != tp.left && t != tp.right)
            return false;
        if (tl != null && (tl.parent != t || tl.hash > t.hash))
            return false;
        if (tr != null && (tr.parent != t || tr.hash < t.hash))
            return false;
        if (t.red && tl != null && tl.red && tr != null && tr.red)
            return false;
        if (tl != null && !checkTreeNode(tl))
            return false;
        if (tr != null && !checkTreeNode(tr))
            return false;
        return true;
    }

}
