HashMap源码分析,转载请注明出处,谢谢

/*
 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.util;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 赵泉伟原创,转载请注明出处,谢谢
 */
public class HashMap<K,V> extends AbstractMap<K,V>
        implements Map<K,V>, Cloneable, Serializable {

    private static final long serialVersionUID = 362498820763181265L;

    /*
     * Implementation notes.
     *
     * This map usually acts as a binned (bucketed) hash table, but
     * when bins get too large, they are transformed into bins of
     * TreeNodes, each structured similarly to those in
     * java.util.TreeMap. Most methods try to use normal bins, but
     * relay to TreeNode methods when applicable (simply by checking
     * instanceof a node).  Bins of TreeNodes may be traversed and
     * used like any others, but additionally support faster lookup
     * when overpopulated. However, since the vast majority of bins in
     * normal use are not overpopulated, checking for existence of
     * tree bins may be delayed in the course of table methods.
     *
     * Tree bins (i.e., bins whose elements are all TreeNodes) are
     * ordered primarily by hashCode, but in the case of ties, if two
     * elements are of the same "class C implements Comparable<C>",
     * type then their compareTo method is used for ordering. (We
     * conservatively check generic types via reflection to validate
     * this -- see method comparableClassFor).  The added complexity
     * of tree bins is worthwhile in providing worst-case O(log n)
     * operations when keys either have distinct hashes or are
     * orderable, Thus, performance degrades gracefully under
     * accidental or malicious usages in which hashCode() methods
     * return values that are poorly distributed, as well as those in
     * which many keys share a hashCode, so long as they are also
     * Comparable. (If neither of these apply, we may waste about a
     * factor of two in time and space compared to taking no
     * precautions. But the only known cases stem from poor user
     * programming practices that are already so slow that this makes
     * little difference.)
     *
     * Because TreeNodes are about twice the size of regular nodes, we
     * use them only when bins contain enough nodes to warrant use
     * (see TREEIFY_THRESHOLD). And when they become too small (due to
     * removal or resizing) they are converted back to plain bins.  In
     * usages with well-distributed user hashCodes, tree bins are
     * rarely used.  Ideally, under random hashCodes, the frequency of
     * nodes in bins follows a Poisson distribution
     * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
     * parameter of about 0.5 on average for the default resizing
     * threshold of 0.75, although with a large variance because of
     * resizing granularity. Ignoring variance, the expected
     * occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
     * factorial(k)). The first values are:
     *
     * 0:    0.60653066
     * 1:    0.30326533
     * 2:    0.07581633
     * 3:    0.01263606
     * 4:    0.00157952
     * 5:    0.00015795
     * 6:    0.00001316
     * 7:    0.00000094
     * 8:    0.00000006
     * more: less than 1 in ten million
     *
     * 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
     * (method TreeNode.root()).
     *
     * All applicable internal methods accept a hash code as an
     * argument (as normally supplied from a public method), allowing
     * them to call each other without recomputing user hashCodes.
     * Most internal methods also accept a "tab" argument, that is
     * normally the current table, but may be a new or old one when
     * resizing or converting.
     *
     * When bin lists are treeified, split, or untreeified, we keep
     * them in the same relative access/traversal order (i.e., field
     * Node.next) to better preserve locality, and to slightly
     * simplify handling of splits and traversals that invoke
     * iterator.remove. When using comparators on insertion, to keep a
     * total ordering (or as close as is required here) across
     * rebalancings, we compare classes and identityHashCodes as
     * tie-breakers.
     *
     * The use and transitions among plain vs tree modes is
     * complicated by the existence of subclass LinkedHashMap. See
     * below for hook methods defined to be invoked upon insertion,
     * removal and access that allow LinkedHashMap internals to
     * otherwise remain independent of these mechanics. (This also
     * requires that a map instance be passed to some utility methods
     * that may create new nodes.)
     *
     * The concurrent-programming-like SSA-based coding style helps
     * avoid aliasing errors amid all of the twisty pointer operations.
     */

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //默认初始容量1<<4 = 1x16=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;//扩容因子默认0.75

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;//切换树形结构hash冲突的阈值

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;//切换链表结构hash冲突的阈值

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;//数据进行结构转换的阈值

    /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    static class Node<K,V> implements Map.Entry<K,V> {//静态内部类,用于维护链表
        final int hash;//hash值
        final K key;//key
        V value;//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; }//获取key
        public final V getValue()      { return value; }//获取value
        public final String toString() { return key + "=" + value; }//获取key=value的组合字符串

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }//获取hashcode

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

        public final boolean equals(Object o) {//重写equals方法
            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 utilities -------------- */

    /**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
    static final int hash(Object key) {//根据key算出对应的hashcode
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }


    /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 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;
    }

    /* ---------------- Fields -------------- */

    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    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;

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

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

    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    int threshold;

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

    /* ---------------- Public operations -------------- */

    /**
     * Constructs an empty <tt>HashMap</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 HashMap(int initialCapacity, float loadFactor) {//有参构造方法
        if (initialCapacity < 0)//如果传入的容量大小小于0则抛出异常
            throw new IllegalArgumentException("Illegal initial capacity: " +
                    initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)//如果传入的容量大于最大值,则默认为最大值
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))//如果传入的扩容因子小于等于0或者非数字则抛出异常
            throw new IllegalArgumentException("Illegal load factor: " +
                    loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);//根据传入的容量计算出临界值
    }

    /**
     * Constructs an empty <tt>HashMap</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 HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }//不指定扩容因子则默认0.75

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }//无惨构造器默认扩容因子0.75



    /**
     * 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;
    }//获取map的总容量

    /**
     * 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;
    }//判断map是否为空,根据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) {//根据传入的key获取value
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;//获取不到返回null否则返回value
    }

    /**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node<K,V> getNode(int hash, Object key) {//根据hash值和key获取node节点
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;//定义相关局部变量
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (first = tab[(n - 1) & hash]) != null) {//判断map数组是否为空
            if (first.hash == hash && // 判断传入的key和hash值是否与链表第一个节点一致,如果是则返回
                    ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {//否则取下一个节点
                if (first instanceof TreeNode)//判断类型是否是treeNode
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);//如果是则调用treenode的相关方法并返回
                do {//否则循环遍历链表找出key相等的node并返回
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);//循环判断条件e.next不为空
            }
        }
        return null;//否则找不到即返回null
    }

    /**
     * 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 getNode(hash(key), key) != null;//判断getNode方法是否返回null
    }//判断map中是否包含某个key

    /**
     * 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) {//put操作
        return putVal(hash(key), key, value, false, true);//调用put操作方法
    }

    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {//put调用方法
        Node<K,V>[] tab; Node<K,V> p; int n, i;//定义相关局部变量
        if ((tab = table) == null || (n = tab.length) == 0)//如果map当前为空则需要进行初始化
            n = (tab = resize()).length;//map的初始化扩容并不是在创建对象的时候而是在使用的时候
        if ((p = tab[i = (n - 1) & hash]) == null)//如果根据算出的hash在当前数组下标没有数据
            tab[i] = newNode(hash, key, value, null);//则直接创建一个node对象并赋值到当前位置
        else {//否则
            Node<K,V> e; K k;//定义相关局部变量
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;//如果hash值key值都相等,则用当前位置的节点p赋值给节点e保存起来
            else if (p instanceof TreeNode)//如果p是treenode的实例则调用treenode的相关方法
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {//否则遍历整个链表
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {//如果当前链表循环到最后一个节点
                        p.next = newNode(hash, key, value, null);//则将新生成的节点放在链表最尾部
                        if (binCount >= TREEIFY_THRESHOLD - 1) // 如果链表元素个数大于临界值
                            treeifyBin(tab, hash);//则转换成树形结构
                        break;//跳出循环
                    }
                    if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))//如果遍历到的对象与传入的key相等并且hash值也相等
                        break;//则跳出循环
                    p = e;//并且将该节点赋值给p
                }
            }
            if (e != null) { // 如果遍历到的节点e对象不为空,如果为空则代表不是替换旧值的操作而是新增节点
                V oldValue = e.value;//先取出旧的value保存起来
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;//用新的value替换旧的
                afterNodeAccess(e);//空实现,HashMap的子类会重写该方法
                return oldValue;//返回原先的值
            }
        }
        ++modCount;//修改一次数自增
        if (++size > threshold)//如果当前的容量大于临界点
            resize();//调用扩容
        afterNodeInsertion(evict);//空实现,HashMap的子类会重写该方法
        return null;//返回null
    }

    /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    final Node<K,V>[] resize() {//扩容
        Node<K,V>[] oldTab = table;//原先的数组
        int oldCap = (oldTab == null) ? 0 : oldTab.length;//获取旧数组的容量大小为空则是0否则取length
        int oldThr = threshold;//取出原先的临界点
        int newCap, newThr = 0;
        if (oldCap > 0) {//如果oldCap大于0
            if (oldCap >= MAXIMUM_CAPACITY) {//并且大于等于最大容量
                threshold = Integer.MAX_VALUE;//则将Integer最大值置为最大容量
                return oldTab;//返回原先数组
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)//如果旧容量扩容2倍并小于最大容量并且旧容量大于默认容量
                newThr = oldThr << 1; // 则将新的临界点也扩大两倍
        }
        else if (oldThr > 0) // 如果旧的阈值大于0则将旧的阈值置为新容量
            newCap = oldThr;
        else {              //否则将新容量置为当前默认容量
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//新的临界点=0.75x16
        }
        if (newThr == 0) {//如果新的临界值为0
            float ft = (float)newCap * loadFactor;//则重新用新的容量进行计算
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                    (int)ft : Integer.MAX_VALUE);//新容量小于最大容量并且计算后的临街点小于最大容量则使用ft否则取Integer最大值
        }
        threshold = newThr;//将最新的临界值置为当前临界值
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//以新的容量创建一个数组
        table = newTab;//将创建的数组置为当前数组
        if (oldTab != null) {//如果旧的数组不为空
            for (int j = 0; j < oldCap; ++j) {//遍历旧数组
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {//遍历到的节点对象不为空
                    oldTab[j] = null;//将原先数组置为空,方便虚拟机回收
                    if (e.next == null)//如果当前节点next为空则代表节点只有一个node
                        newTab[e.hash & (newCap - 1)] = e;//将当前节点对象根据hash算法算出在新数组里的位置并赋值
                    else if (e instanceof TreeNode)//否则如果是treenode对象则调用treenode相关方法
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { //否则
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;//定义相关变量
                        do {//遍历链表
                            next = e.next;//获取下一个节点
                            if ((e.hash & oldCap) == 0) {//如果算出的结果为0
                                if (loTail == null)//如果loTail是空
                                    loHead = e;//则将节点e置为lohead
                                else//否则
                                    loTail.next = e;//否则将节点e置为loTail.next
                                loTail = e;
                            }
                            else {//如果算出的结果不是0
                                if (hiTail == null)//如果hiTail是空
                                    hiHead = e;//则将节点e置hiHead
                                else//否则
                                    hiTail.next = e;//否则将节点e置为hiTail.next
                                hiTail = e;
                            }
                        } while ((e = next) != null);//循环判断条件next!=null
                        if (loTail != null) {//如果loTail非空
                            loTail.next = null;//loTail.next置为空
                            newTab[j] = loHead;//loHead赋值给当前数组
                        }
                        if (hiTail != null) {//如果hiTail非空
                            hiTail.next = null;//hiTail.next置为空
                            newTab[j + oldCap] = hiHead;//hiHead赋值给当前数组
                        }
                    }
                }
            }
        }
        return newTab;//返回新生成的数组对象
    }

    /**
     * Replaces all linked nodes in bin at index for given hash unless
     * table is too small, in which case resizes instead.
     */
    final void treeifyBin(Node<K,V>[] tab, int hash) {//转换成树形结构
        int n, index; Node<K,V> e;//定义局部变量
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)//如果数组为空或者数组长度小于需要转成树形结构的阈值
            resize();//则进行扩容
        else if ((e = tab[index = (n - 1) & hash]) != null) {//否则
            TreeNode<K,V> hd = null, tl = null;//定义局部变量
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);//将node对象转换成treeNode对象
                if (tl == null)//如果t1为空
                    hd = p;//则将生成的treenode对象赋值给你hd
                else {//否则
                    p.prev = tl;//将上一个生成的对象t1置为当前对象的prev
                    tl.next = p;//将当前生成的对象p置为上一个对象的next
                    //串联起来
                }
                tl = p;//将当前对象置为t1
            } while ((e = e.next) != null);//循环判断条件next!=null
            if ((tab[index] = hd) != null)//如果hd不为空
                hd.treeify(tab);//则进行树形链表的追加
        }
    }



    /**
     * 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) {//根据key删除元素并返回删除的元素
        Node<K,V> e;//定义局部变量
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
                null : e.value;//调用删除元素的方法,如果返回空则返回null,否则返回value
    }

    /**
     * Implements Map.remove and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to match if matchValue, else ignored
     * @param matchValue if true only remove if value is equal
     * @param movable if false do not move other nodes while removing
     * @return the node, or null if none
     */
    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {//根据相关参数删除节点
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {//map不为空并且算出当前key的hash存储下标
            Node<K,V> node = null, e; K k; V v;//定义局部变量
            if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))//如果hash和key都相同
                node = p;//找到相同的将p节点置为node
            else if ((e = p.next) != null) {//否则进行遍历
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);//如果是treenode类型则执行treenode相关方法
                else {//否则进行遍历
                    do {
                        if (e.hash == hash &&
                                ((k = e.key) == key ||
                                        (key != null && key.equals(k)))) {
                            node = e;//如果找到hash和key相等的则 将遍历到的e置为node
                            break;//跳出循环
                        }
                        p = e;//否则将e置为p
                    } while ((e = e.next) != null);//循环判断条件next!=null
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                    (value != null && value.equals(v)))) {//针对node和value的判断
                if (node instanceof TreeNode)//如果是treenode则执行treenode相关方法
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)//如果node==p
                    tab[index] = node.next;//则用node.next直接进行覆盖
                else//否则
                    p.next = node.next;//用待删除节点的next直接置为p的next
                ++modCount;//修改次数自增
                --size;//map的size自减
                afterNodeRemoval(node);//空实现
                return node;//返回被删除的node
            }
        }
        return null;//没找到删除的元素则返回null
    }

    /**
     * Removes all of the mappings from this map.
     * The map will be empty after this call returns.
     */
    public void clear() {//清空map
        Node<K,V>[] tab;//定义局部变量
        modCount++;//修改次数自增
        if ((tab = table) != null && size > 0) {//如果map不为空
            size = 0;//首先将size置为0
            for (int i = 0; i < tab.length; ++i)//遍历数组
                tab[i] = null;//将遍历到的数据置为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) {//判断map中是否包含某个value
        Node<K,V>[] tab; V v;//定义局部变量
        if ((tab = table) != null && size > 0) {//如果map不为空
            for (int i = 0; i < tab.length; ++i) {//遍历整个map
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {//遍历链表
                    if ((v = e.value) == value ||
                            (value != null && value.equals(v)))//如果找到相同的值
                        return true;//返回true;
                }
            }
        }
        return false;//否则 返回false
    }

    /**
     * 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.
     *
     * @return a set view of the keys contained in this map
     */
    public Set<K> keySet() {//返回一个set集合
        Set<K> ks = keySet;
        if (ks == null) {//如果set是空,则创建一个set对象
            ks = new KeySet();
            keySet = ks;
        }
        return ks;
    }

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

    /**
     * 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.
     *
     * @return a view of the values contained in this map
     */
    public Collection<V> values() {//获取当前map里的value集合
        Collection<V> vs = values;//value集合
        if (vs == null) {//如果为空,则创建一个集合对象
            vs = new Values();
            values = vs;
        }
        return vs;//返回
    }

    final class Values extends AbstractCollection<V> {//Values内部类
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<V> iterator()     { return new ValueIterator(); }
        public final boolean contains(Object o) { return containsValue(o); }
        public final Spliterator<V> spliterator() {
            return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
        }



    // Overrides of JDK8 Map extension methods

    @Override
    public V getOrDefault(Object key, V defaultValue) {//根据传入的key获取value,如果获取不到,则返回传入的defaultValue
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;//根据三目运算符获取对应的值
    }



    @Override
    public boolean remove(Object key, Object value) {//根据key和value删除元素
        return removeNode(hash(key), key, value, true, true) != null;//调用具体的删除方法
    }

    @Override
    public boolean replace(K key, V oldValue, V newValue) {//根据key和oldvalue进行value的替换
        Node<K,V> e; V v;//定义局部变量
        if ((e = getNode(hash(key), key)) != null &&
                ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {//根据key和oldvalue找到对应的值
            e.value = newValue;//用传入的newValue进行替换
            afterNodeAccess(e);
            return true;//返回true
        }
        return false;//否则false
    }

    @Override
    public V replace(K key, V value) {//根据key来替换value并返回旧的值
        Node<K,V> e;//定义局部变量
        if ((e = getNode(hash(key), key)) != null) {//根据key找到节点
            V oldValue = e.value;//将旧的value保存起来
            e.value = value;//替换
            afterNodeAccess(e);
            return oldValue;//返回
        }
        return null;//没替换到则返回null
    }

     

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值