HashMap源码阅读

属性


    /**
     * The default initial capacity - MUST be a power of two.
     * 默认容量必须是2的n次方,默认大小为16
     */
    static final int DEFAULT_INITIAL_CAPACITY = 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.
     * 最大容量2的30次方
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     * 默认负载因子,默认的扩容标准,超过总容量的3/4开始扩容
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     * 数组的个数,长度同样必须是2的n次方
     */
    transient Entry[] table;

    /**
     * The number of key-value mappings contained in this map.
     * map中所有元素的个数
     */
    transient int size;

    /**
     * The next size value at which to resize (capacity * load factor).
     * 下一次rehash的阀值
     * @serial
     */
    int threshold;

    /**
     * The load factor for the hash table.
     *负载因子,默认为0.75
     * @serial
     */
    final float loadFactor;

    /**
     * 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).
     * hashmap被修改的次数
     * 此处的修改是指元素个数的修改,或者是指修改内部结构例如:rehash
     * 该属性主要用于迭代器的快速失败判断
     */
    transient volatile int modCount;

方法


构造器

    /**
     * 指定初始容量和负载因子
     */
    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))//loadFactor<0或者不是一个值
            throw new IllegalArgumentException("Illegal load factor:"+loadFactor);

        /*
         * 下边的逻辑是找一个2的几次方的数,该数刚刚大于initialCapacity
         * eg.当指定initialCapacity为17,capacity就是32(2的五次方),而2的四次方(16)正好小于17
         */
        int capacity = 1;
        while (capacity < initialCapacity)
            capacity <<= 1;// capacity = capacity<<1

        this.loadFactor = loadFactor;
        threshold = (int)(capacity * loadFactor);
        table = new Entry[capacity];
        init();
    }

    /**
     * 指定初始容量
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);//调用上边的双参构造器
    }

put方法

/**
     * 向map中添加新Entry
     * 步骤:
     * 1)HashMap可以添加null的key,key==null的Entry只会放在table[0]中,但是table[0]不仅仅可以存放key==null的Entry
     * 1.1、遍历table[0]中的Entry链,若有key==null的值就用新值覆盖旧值,并返回旧值value,
     * 1.2、若无,执行addEntry方法,用新的Entry替换掉原来旧的Entry赋值给table[0],而旧的Entry作为新的Entry的next,执行结束后,返回null
     * 2)添加key!=null的Entry时,
     * 2.1、先计算key.hashCode()的hash值,
     * 2.2、然后计算出将要放入的table的下标i,
     * 2.3、之后遍历table[i]中的Entry链,若有相同key的值就用新值覆盖旧值,并返回旧值value,
     * 2.4、若无,执行addEntry方法,用新的Entry替换掉原来旧的Entry赋值给table[i],而旧的Entry作为新的Entry的next,执行结束后,返回null
     */
    public V put(K key, V value) {
        if (key == null)                
            return putForNullKey(value);     //将空key的Entry加入到table[0]中
        int hash = hash(key.hashCode());     //计算key.hashcode()的hash值,hash函数由hashmap自己实现
        int i = indexFor(hash, table.length);//获取将要存放的数组下标
        /*
         * for中的代码用于:当hash值相同且key相同的情况下,使用新值覆盖旧值(其实就是修改功能)
         */
        for (Entry<K, V> e = table[i]; e != null; e = e.next) {//注意:for循环在第一次执行时就会先判断条件
            Object k;
            //hash值相同且key相同的情况下,使用新值覆盖旧值
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                //e.recordAccess(this);
                return oldValue;//返回旧值
            }
        }

        modCount++;
        addEntry(hash, key, value, i);//增加一个新的Entry到table[i]
        return null;//如果没有与传入的key相等的Entry,就返回null
    }

putForNullKey方法

/**
     * 增加null的key到table[0]
     */
    private V putForNullKey(V value) {
        //遍历第一个数组元素table[0]中的所有Entry节点
        for (Entry<K, V> e = table[0]; e != null; e = e.next) {
            if (e.key == null) {//用新值覆盖旧值
                V oldValue = e.value;
                e.value = value;
                //e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(0, null, value, 0);//将新节点Entry加入到Entry[]中
        return null;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值