HashMap源码详细解释

package NewCollections;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.AbstractMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.HashMap.Node;
import java.util.HashMap.TreeNode;
/** * HashMap继承了AbstractMap,实现了Map,Cloneable以及Serializable接口,所以支持克隆以及序列化操作,在序列化的时候自己实现了readObject以及 * writeObject,这是出于节省内存的目的 * @author liliang * */
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //HashMap默认大小为16
    static final int MAXIMUM_CAPACITY = 1 << 30; //HashMap最大容量2的30次方
    static final float DEFAULT_LOAD_FACTOR = 0.75f; //默认加载因子0.75,增加此值,能够利用内存,但是查找效率会降低,调低此值,查找效率上升,但浪费内存,一般取默认值
    static final int TREEIFY_THRESHOLD = 8;//当链表中的碰撞次数大于等于8时,将链表转变为红黑树
    static final int UNTREEIFY_THRESHOLD = 6;//当链表中的数目小于等于6,将红黑树转变为链表
    //当好多bin被映射到同一个桶时,如果这个桶中bin的数量小于TREEIFY_THRESHOLD当然不会转化成树形结构存储;
    //如果这个桶中bin的数量大于了 TREEIFY_THRESHOLD ,但是capacity小于MIN_TREEIFY_CAPACITY 则依然使用链表结构进行存储,
    //如果capacity大于了MIN_TREEIFY_CAPACITY ,则会进行树化。
    static final int MIN_TREEIFY_CAPACITY = 64;
    /**HashMap中的静态内部类(1.静态内部类的创建不需要外围类对象 2.不能使用任何外围类的非静态变量和方法) * Node数据结构即HashMap存储的元素,也就是多次提到的bin,这里只介绍其中重要的方法,简单的方法就不进行说明 * Map.Entry是Map接口中定义的接口,表示Map中存储的条目 */
    static class Node<K,V> implements Map.Entry<K,V> {
        //将key的hashCode与value的hashCode进行异或运算
        public final int hashCode() { 
            return Objects.hashCode(key) ^ Objects.hashCode(value);//这里调用了Objects中的hashCode方法,而Objects中的方法又调用了Object中的hashCode(native)
        }
        public final boolean equals(Object o) {
            if (o == this) //如果对象o的地址与this对象地址相同,则返回true
                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值,将key的hashCode值的高16位与低16位进行异或运算 */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); //hashCode()是native方法
    }
    /** * 如果x的类型是Comparable接口的类型,则返回c,c是x的Class;如果x不是,则返回null */
    static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; Type t; ParameterizedType p; //Type是java所有类型的公共接口,ParameterizedType是其的一个实现,表示泛型类型,例如Collection<String>
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {//getGenericInterfaces返回Class c实现的接口
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() == //getRawType获取泛型的基本类型
                         Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null && //getActualTypeArguments获取泛型中的参数
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }

    @SuppressWarnings({"rawtypes","unchecked"}) // 压制没有参数化的警告
    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }
    //给定cap,返回大于cap且距离cap最近的2的整数幂,计算结果为threshold,它表示下一次resize时size的值。
    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;
    }
    transient Node<K,V>[] table;//HashMap底层采用的数组
    transient int modCount;//当修改HashMap的结构时,改变此值,用于fail-fast,其他的容器大部分都有此值,如TreeMap 
    int threshold;//下一次resize后的size值,当容量达到(capacity * load factor)后进行resize
    final float loadFactor;
    /******HashMap初始化方式******/
    public HashMap(int initialCapacity, float loadFactor){/*在这里实现的threshold等于tableSizeFor(initialCapacity)*/}
    public HashMap(int initialCapacity){}
    public HashMap() {}
    public HashMap(Map<? extends K, ? extends V> m) {}
    //http://www.cnblogs.com/dongkuo/p/4960550.html 参考此链接,可以查看这个函数说明
    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; //这里是计算m的capacity
                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);
            }
        }
    }
    //获取元素的核心
    final Node<K,V> getNode(int hash, Object key) { //这里的hash是用上文中的hash方法进行的计算,计算key的hash
        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) {//查找hash值在table中的位置采用(n-1) & hash 
            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;
    }
    //添加元素的核心代码
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
            boolean evict) {
         Node<K,V>[] tab; Node<K,V> p; int n, i;
         if ((tab = table) == null || (n = tab.length) == 0)
             n = (tab = resize()).length;
         if ((p = tab[i = (n - 1) & hash]) == null)
             tab[i] = newNode(hash, key, value, null);
         else {
             Node<K,V> e; K k;
             if (p.hash == hash &&
                 ((k = p.key) == key || (key != null && key.equals(k))))
                 e = p;
             else if (p instanceof 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) // -1 for 1st
                             treeifyBin(tab, hash);
                         break;
                     }
                     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; //修改modCount用于fail-fast
         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;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            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
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        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 { //这部分代码可以保证HashMap经过resize之后仍然能够保证顺序,不想JDK8之前的实现,会将链表中的顺序转换
                            next = e.next;
                            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;
    }
}
    原文作者:benjaminlee1
    原文地址: https://blog.csdn.net/benjaminlee1/article/details/53138823
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞