Java基础之HashMap1.7源码解读

HashMap jdk1.7

三个基础变量

//必须是2的幂次方,初始大小为16
 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
 //装载的元素/容量
 static final int MAXIMUM_CAPACITY = 1 << 30;
 static final float DEFAULT_LOAD_FACTOR = 0.75f
 //数量到达阈值时扩容,大小为装载因子乘以capacity
 int threshold;

为什么默认容量必须是2的幂次方?
答:hashcode&(length-1)bu
容量是2的幂次方 length-1 所有位都是1,可以减少hash碰撞
如果与的某一位为0,那么与这一位与永远不能得到1,那么某些位置就永远空出来

初始化

初始化容量和装载因子

 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();
    }

节点信息

1.7以前是用entry对象存储信息
本质上是一个entry数组

   static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;//下一节点
        int hash;//hash值

        /**
         * Creates new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }/**
     * Adds a new entry with the specified key, value and hash code to
     * the specified bucket.  It is the responsibility of this
     * method to resize the table if appropriate.
     *
     * Subclass overrides this to alter the behavior of put method.
     */
     //加入一个新的对象
    void addEntry(int hash, K key, V value, int bucketIndex) {
        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);
    }

    /**
     * Like addEntry except that this version is used when creating entries
     * as part of Map construction or "pseudo-construction" (cloning,
     * deserialization).  This version needn't worry about resizing the table.
     *
     * Subclass overrides this to alter the behavior of HashMap(Map),
     * clone, and readObject.
     */
     //新建节点
    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++;
    }

put方法

头插法

 public V put(K key, V value) {
 		//当table不存在的时候
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
        //key为null 插入为0的桶里有且只能有一个空值
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);
		//插入的key已经存在
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            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;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

inflateTable方法

    /**
     * Inflates the table.
     * table扩张
     */
    private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        //不管初始容量设的是不是2的幂次,都会自动转为2的幂次
        int capacity = roundUpToPowerOf2(toSize);
		//扩张的阈值为capacity*loadFactor
        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        //table是一个Entry数组
        table = new Entry[capacity];
        initHashSeedAsNeeded(capacity);
    }

table是一个Entry数组
不管初始容量设的是不是2的幂次,都会自动转为2的幂次

插入空值的方法

    private V putForNullKey(V value) {
        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);
        return null;
    }

空值只能插入到位于0的bucket。且只能有一个,再次插入会覆盖value

hash

null的hash值永远为0
算出来的hash值进行右移,异或之后,让高位也参与运算,减少hash碰撞

    final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }

        h ^= k.hashCode();

        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

indexFor()除法hash

为什么容量必须是2的非0幂次方的原因

 static int indexFor(int h, int length) {
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
        return h & (length-1);
    }

addEntry()

当元素的数目大于threshold=capacity*loadFactor 时,2倍扩容,为什么2倍等价于capacity必须是2的非0幂次方 index=hash&(length-1)
1.7扩容后的元素迁移是重新计算一次hash

void addEntry(int hash, K key, V value, int bucketIndex) {
		//需要扩容就进行迁移
        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);
    }

resize()

void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        //越界情况
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

        Entry[] newTable = new Entry[newCapacity];
        //旧表迁移到新表
        transfer(newTable, initHashSeedAsNeeded(newCapacity));
        table = newTable;
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }

transfer()

旧表迁移到新表,重新计算hash值

    void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                //重新计算hash值
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

put 方法总结

put(){
//1.放入空值的方法
putForNullKey();
//2.计算hash值
indexforhash();
//3.插入已存在值得处理
返回旧的值
//4.添加新节点
//i是插入的位置
addEntry(hash, key, value, i){
	//1.对象个数大于threshold或者发生碰撞时扩容
	resize(){
		//迁移数据
		transfer()
		头插法
		}
	}
	newEntry() 头插法
}

1.7问题

循环链表问题
1.丢失数据 数据5丢失
2.链表成环
图片来源马士兵公开课
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值