HashMap实现原理理解&分析

1.构造器
不难可以看出HashMap的存储是由entry数组组成的,默认大小16。


 public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
        table = new Entry[DEFAULT_INITIAL_CAPACITY];
        init();
 }


2.put

hashmap中存储数据,如果key为null,总是存入Entry[0]中。

先算出key的hash值,再调用indexFor算出数组下标值,再放入相应的table[i].

    public V put(K key, V value) {
	if (key == null)
	    return putForNullKey(value);
        int hash = <span style="color:#ff0000;">hash(key.hashCode())</span>;
        int i = <span style="background-color: rgb(255, 0, 0);">indexFor(hash, table.length);</span>
        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++;
        <span style="background-color: rgb(255, 0, 0);">addEntry(hash, key, value, i);</span>
        return null;
    }

 static int indexFor(int h, int length) {
        return h & (length-1);
    }


当indexFor算出来的下标值一样时,是否会造成覆盖的危险呢?

答案当然是否定的,HashMap中用到链式存储的方式,例如,C<Entry>.next = B<Entry> ,B<Entry>.next = A<Entry> ,

所以说table数组中存储的的是最后插入的元素,不存在覆盖的危险。


 void addEntry(int hash, K key, V value, int bucketIndex) {
	Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
        if (size++ >= threshold)
            resize(2 * table.length);
    }



3.get


    public V get(Object key) {
	if (key == null)
	    return getForNullKey();
        int hash = hash(key.hashCode());
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
                return e.value;
        }
        return null;
    }


4. resize

HashMap的公共溢出区的实现如下:

当哈希表的容量超过shreshold的时候,hashmap开始扩容,并创建一张新表,将原表的数据映射到新表中。

当哈希表接近等于Integer最大值的时,hashmap的容量也开始接近于2的30次方,将不在扩容。

    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);
        table = newTable;
        threshold = (int)(newCapacity * loadFactor);
    }



综上所述,用以下方法解决hash冲突,

  1. 开放定址法(线性探测再散列,二次探测再散列,伪随机探测再散列)
  2. 再哈希法
  3. 链地址法
  4. 建立一个公共溢出区




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值