HashMap源码学习(基于jdk1.8)

wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==
HashMap数据结构示意图

//默认初始化容量,必须是2的幂次

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;


//最大容量,如果指定其它较大值时,则必须是2的幂次,且小于等于1<<30

static final int MAXIMUM_CAPACITY = 1 << 30;


//默认负载因子

static final float DEFAULT_LOAD_FACTOR = 0.75f;


//树化结构最小链节点数,即单个表节点上的链节点超过8个时才会转换为红黑树进行存储

static final int TREEIFY_THRESHOLD = 8;


//树结构转为链结构时的树节点数,即与上面的参数相对应

static final int UNTREEIFY_THRESHOLD = 6;


//树化结构的最小表节点数,即小于这个数时,不会进行链表转红黑树,而是给表扩容

static final int MIN_TREEIFY_CAPACITY = 64;

内部类Node<K,V>不再赘述,比较简单

/*
* 计算node在map中存取时使用的hash值
*/
    static final int hash(Object key) {
        int h;
        //当key不为null时,将key的hashcode的前16位和后16位做异计算返回
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
/*
* 判断若x实现了Comparable<C>接口,则返回x的类型,否则返回空
*/

    static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() ==
                         Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }
/*
* 若x为空或者不是kc类型则返回0,否则返回x和k的对比值
*/

    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }
/*
* 计算返回table的size,结果值为大于或等于cap的最小2的幂次
*/

    static final int tableSizeFor(int cap) {
// 计算前减1,防止cap已经是2的幂次时获取的值为cap*2
        int n = cap - 1;
//以下操作即将cap的二进制值后续值全部补1,如01000010,则补充后为01111111
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
//返回计算值+1,得到大于等于cap的最小2幂次值
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
// 存储链/树的表格,首次使用时初始化大小,且大小必须为2的幂次
    transient Node<K,V>[] table;
//存储值的集合,用于keySet() 和 values()方法
    transient Set<Map.Entry<K,V>> entrySet;
// hashmap实际存储的节点数,put或remove等操作时都会更新
    transient int size;
//每次成功调整hashmap结构时增加一次,主要用于防止在map上建立子视图时进行调整结构操作
    transient int modCount;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章