HashMap源码

继承类:AbstractMap
实现接口:Map、Cloneable
Map:将key-value映射为对象,接口取代了Dictionary类,
AbstractMap实现了Map,减少实现Map接口时的工作量
Cloneable实现此接口的类可以进行拷贝操作
 
重要说明:
1、异或操作:
x是二进制数0101,y是二进制数1011;
则x ^ y=1110
2、每个键值对Node节点的hashCode=Objects.hashCode(key) ^ Objects.hashCode(value);(异或操作)
3、判断两个键值Node节点相等的条件为:
如果Node<K,V> A == Node<K,V> B,则返回true
如果A节点继承了Map.Entry接口,并且A.key.equals(B.key) 并且A.value.equals(B.value) ,则返回true
 
代码翻译:
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

    初始大小16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    最大容量2的30次方
    static final int MAXIMUM_CAPACITY = 1 << 30;

    容量扩大因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;


    哈希节点,节点中保存了key、value、hash、next节点值
    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;
        }
    }

    根据key计算hash值
    static final int hash(Object key) {
        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 -------------- */

    初始化数组
    transient Node<K,V>[] table;

    已Set结构保存每个Map.Entry<K,V>节点
    transient Set<Map.Entry<K,V>> entrySet;

    Map大小
    transient int size;

    Map修改次数
    transient int modCount;

    size=(capacity * load factor)
    int threshold;

    哈希表的增长因子
    final float loadFactor;


    根据初始化容量以及增长因子构建空的HasHMap,
    public HashMap(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);
    }

    构建空的HasHMap,
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    构建空的HasHMap,增长因子=0.75
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    将指定Map对象保存到已存在的HashMap
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

    将指定Map对象保存到已存在的HashMap
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }


    返回指定key的value或者返回null
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    hash相同并且key相等,则返回Node节点
    先获得table数组,从数组0开始遍历,
    判断每个数组的hash值与传入的hash是否相等(优先判断),并且key相等,则数组节点
    final Node<K,V> getNode(int hash, Object key) {
        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) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
    
    //根据保存key与value,如果key已经存在,则value替换oldvalue
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    
    根据public V put(K key, V value)方法调用putVal(hash(key), key, value, false, true)进行说明
    //保存key与value,对传入参数进一步说明:
        hash:key的hash值
        key:key值
        value:key对应的需要保存的值
        onlyIfAbsent:如果为true,表示已经存在key,则不替换oldvalue,如果为false,表示如果key已经存在,可以使用newValue替换oldValue
        evict:(先不考虑)
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //数组对象为空,或者数组长度为0,设置新数组的长度
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //key,value、hash创建Node节点,设置在tab[i]数组上
        //上一步骤n = tab.length中,n获得了当前数组的长度,
        //如果table数据为空或者长度为0,则会根据调用resize()重新初始化一个数组
        //如果根据hash在数组上找不到索引,则新建一个NewNode节点,并把NewNode节点复制到数组节点上
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            //如果hash、key都相等,则设置e节点=数组中p节点
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                //如果p节点是TreeNode类型的节点,则调用TreeNode类下的putTreeVal方法进行设置key、value
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                //如果p节点即不是数组上的节点,也不是TreeNode类型的节点,表示p为数组链表中的节点,
                //循环数组后的链表,查找要找的节点(hash、key都相等的节点)
                for (int binCount = 0; ; ++binCount) {
                    //如果最后节点的next为空,表示没有其他节点了,则新建一个newNode节点
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //如果查找到了hash、key都相等的节点,则把查找到的节点e复制给p节点
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

    重新设置数组大小
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        //获得原有数组长度
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //获得 临界值
        int oldThr = threshold;
        int newCap, newThr = 0;
        //如果临界值大于0,则新的数组长度等于临界值
        if (oldCap > 0) {
        //如果原数组长度大于0,并且原数组长度>(1 << 30),则返回原数组长度,同时临界值设置为Integer.MAX_VALUE
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
        //如果原数组长度大于0,并且原数组长度*2 小于Integer.MAX_VALUE 并且 原数组长度大于默认长度16(1<<4),则设置新的数组长度为原数组长度*2
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            //如果以上都不符合,则新的数组长度为10,新的临界值为默认长度10 * 默认因子0.75
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        //如果新的临界值==0,则如果新的数组长度小于Integer.MAX_VALUE并且 新的数组长度*默认因子小于Integer.MAX_VALUE,则新的临界值设置为新的数组长度*默认因子,否则设置为nteger.MAX_VALUE
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        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)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        //
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            //这个逻辑不会触发,如果(e.hash & oldCap) == 0为true,则oldCap=0,表示数组为空
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                //按顺序把原数组节点中每个链表都复制到新数组每个节点的链表
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = 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);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }


    根据执行key删除节点对象
    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

    
    具体说明 public V remove(Object key)方法调用时传递的参数:removeNode(hash(key), key, null, false, true)
    根据具体的节点信息删除Node
    传入参数说明:
        hash:key的hash值
        key:key值
        value:如果matchValue=true,则删除时需要匹配value与根据key和hash取出的value相等才删除
        matchValue:控制是否匹配value,如果为true,则value相等则删除
        movable:如果为false时,删除时不移动其他节点,如果为true,则删除节点时需要移动其他节点
    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) {
            Node<K,V> node = null, e; K k; V v;
            //获取hash获得数组对应的节点判断hash、key是否相等,如果相等则把查找到的节点复制给node
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                //如果节点是TreeNode类型的对象,根据hash和key获得TreeNode节点信息,把查找到的节点复制给node
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                //如果不相等则进行do while循环判断,如果相等则把查找到的节点复制给node
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            如果查找到的节点不为空,在根据参数matchValue来控制是否需要进行值的校验
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)//针对查找的node是TreeNode类型的节点,则使用TreeNode下的removeTreeNode方法删除节点
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)//针对查找到的node节点 等于 数组节点的情况
                    //如果查找到的node节点 等于 数组节点,则把数组节点设置为node节点的下一个节点
                    tab[index] = node.next;
                else
                    //如果不是以上两种情况,则p的next节点设置为node的next节点,这样node节点就不在数组节点后的链表中了
                    p.next = node.next;
                ++modCount;//HashMap操作次数加一
                --size;//HashMap数量减一
                afterNodeRemoval(node);//
                return node;//返回被删除节点,如果没有则返回null
            }
        }
        return null;
    }

    //清空table数组
    public void clear() {
        Node<K,V>[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }

    根据key、value必须与HashMap中完全匹配才可以删除节点数据数据
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }

    
    克隆HashMap的镜像,值不会克隆
    @SuppressWarnings("unchecked")
    @Override
    public Object clone() {
        HashMap<K,V> result;
        try {
            result = (HashMap<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
        result.reinitialize();
        result.putMapEntries(this, false);
        return result;
    }

}

 

 
posted @ 2018-09-06 01:06  使用D  阅读(145)  评论(0编辑  收藏  举报