HashMap

这里写图片描述


   HashMap 初始化4^2容量的table表,加载因子为0.75 ,每个table存储一个hashmapEntry(该entry含一个next引用,形成一个链表)
   每次put(key,value) 判断是否需要扩容,若需要扩容,则重新hash,重新将每一个hashmapentry放置到新的table【i】中,重hash完之后,再对 新插入key hash->i,   createHashmapentry,插入table[i].
//initialCapacity 容量,初始默认值为16,最大为2^30,loadFactor为加载因子,
//当size>initialCapacity*loadFactor时候map在push数据时判断自动扩容为原来2//倍,init()模板方法用于子类。
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;
        threshold = initialCapacity;
        init();
    }

/**
     * 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) {
    //如果table表为空,则初始化表,设置极限容量threshold,设置表容量

        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        //map的key可以为空,默认插入hash值为0的桶处
        if (key == null)
            return putForNullKey(value);
        //key非空,则计算其hash值
        int hash = hash(key);
        //计算其在table表中的索引值下标
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            //遍历下标为i的entry链表(next引用模拟指针)
            //当找到key值相同的entry时,直接将新value替换掉原来的旧value
            //recordAccess(子类使用如linkedhashmap)
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
    //如若插入值新,不存在key已之相等的,则插入entry链表中(next引用模拟指针)
        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

/**
     * Inflates the table.
     */
    private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        //map capacity容易必须为2的整数次幂 
        int capacity = roundUpToPowerOf2(toSize);
        //计算极限容量threshold为容量*加载因子和最大容量之间比较的最小者
        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        //初始化table表
        table = new Entry[capacity];
        initHashSeedAsNeeded(capacity);
    }

    final int hash(Object k) {  
        int h = hashSeed;  
        if (0 != h && k instanceof String) {  
            return sun.misc.Hashing.stringHash32((String) k);  
        }  
        // 调用key的hashCode()方法得到hashCode  
        h ^= k.hashCode();  

        // 对hashCode进行一系列的位移与异或运算并把结果作为hashCode返回  
        h ^= (h >>> 20) ^ (h >>> 12);  
        return h ^ (h >>> 7) ^ (h >>> 4);  
    }  

//将新entry插入entry链表中
void addEntry(int hash, K key, V value, int bucketIndex) {
    //判断是否需要扩容,当table【bucketIndex】不空且当前size>极限容量时
    //自动扩容且判断是否需要重新hash
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }

        createEntry(hash, key, value, bucketIndex);
    }

//扩容时重新hash各entry链表
void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {
            while(null != e) {
            //首先将entry链表中的next entry取出来
                Entry<K,V> next = e.next;
                if (rehash) {
                    //重新计算该entry链的hash值
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                //计算其在新扩容表中的下标索引值
                int i = indexFor(e.hash, newCapacity);
                //将其next引用指向上一次取出来的entry
                e.next = newTable[i];
                //将其放置在 newTable[i]中
                newTable[i] = e;
                //继续将next依次取出来连接之前已经取出来的entry
                e = next;
            }
        }
    }

//将新map插入到entry链表中
void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值