HashMap的进一步理解

本文深入探讨了HashMap的数据结构,包括其内部使用的数组和链表结构、哈希算法、索引计算方法、插入与查找操作的具体流程及源码分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 数据结构

transient Entry[] table;

用数组和链表来实现,实质是链表数组,更进一步说是散列链表数组,因为每一个链表的散列值相同,即Entry的数组,链表和数组的区别见:

http://geeksun.iteye.com/blog/1709418

Entry(Key,value,next)


 2. Entry链表

实际上HashMap存放的对象是Entry对象,Entry相当于HashMap中的实体,Entry有key,value,hash,next属性,key和value都保存在Entry里

        final K key;
        V value;
        Entry<K,V> next;
        final int hash;

 3. 插入元素数据

public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        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;
    }

 代码解读:

 

添加Null键

 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;
 }
 在put()方法中,如果key是null,就放在数组的第一个位置上。

  hash()方法(哈希算法)

static int hash(int h) {
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
}

 这个方法是散列方法(哈希算法),目的是为了生成分布比较均匀的哈希码,进一步了解见

 哈希算法 http://geeksun.iteye.com/blog/513117  和 位移运算 http://geeksun.iteye.com/blog/380032

 indexFor()方法,得出哈希码在Entry数组中的位置

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

 因为是 h & (length-1)返回一个小于length的值,就是在数组中的位置。

 

 对key相同的Entry的处理:

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

 这一段是处理插入相同的key的Entry对象时,把现有value的值更换为新的value值。

 

插入新Entry数据:

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

 如果Entry数组的bucketIndex上已经有Entry存在,就把新的Entry放在bucketIndex位置,原Entry移到新Entry的next指向的位置———在链表头部插入数据,如果bucketIndex位置上没有Entry存在,新插入的Entry的next指向null。

        链表设计——可以看得出这是一个非常优雅的设计。系统总是将新的Entry对象添加到bucketIndex处。如果bucketIndex处已经有了对象,那么新添加的Entry对象将指向原有的Entry对象,形成一条Entry链,但是若bucketIndex处没有Entry对象,也就是e==null,那么新添加的Entry对象指向null,也就不会产生Entry链了。

HashMap使用链表来解决碰撞问题,当两个key的hashcode值一样时,即发生碰撞时,存放在链表的下一个节点中。

 

 当Entry数组的大小超过阀值时(默认75%),容量扩容一倍。

 

 Entry数组的扩容(rehash方法)

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

 数组扩容时,数组的最大容量是1<<30,当数组的容量为1<<30时,阀点值是Integer的最大值MAX_VALUE。

 

迁移旧数组的Entry到新数组

 void transfer(Entry[] newTable) {
        Entry[] src = table;
        int newCapacity = newTable.length;
        for (int j = 0; j < src.length; j++) {
            Entry<K,V> e = src[j];
            if (e != null) {
                src[j] = null;
                do {
                    Entry<K,V> next = e.next;
                    int i = indexFor(e.hash, newCapacity);
                    e.next = newTable[i];
                    newTable[i] = e;
                    e = next;
                } while (e != null);
            }
        }
 }

       在迁移旧数组的Entry到新数组时,链表的Entry的顺序会反过来,从链表的第一个Entry开始,插入到新链表中,第一个Entry存放到了链尾,最后一个Entry加到了链头,这是为了避免尾部遍历(tail traversing)。

 4. 取出Map中的数据

get()方法:根据Key查找Value

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

         查找key对应的value时,先计算出key的hash值,然后遍历Entry链表,如果key的hash值同Entry对象的hash值相等,并且key和Entry的key值相等或key和Entry的key的equals()方法结果为true,就可以确认此key是这个Entry对象的key,返回这个Entry对象的value值。

 5.移除HashMap中的指定数据

 移除Entry链表中的对象

final Entry<K,V> removeEntryForKey(Object key) {
        int hash = (key == null) ? 0 : hash(key.hashCode());
        int i = indexFor(hash, table.length);
        Entry<K,V> prev = table[i];
        Entry<K,V> e = prev;

        while (e != null) {
            Entry<K,V> next = e.next;
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                modCount++;
                size--;
                if (prev == e)
                    table[i] = next;
                else
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
            prev = e;
            e = next;
        }

        return e;
}

 根据参数key,来移除Entry链表中的key对应的Entry对象,remove()方法中,先计算出key的散列值,再根据散列值找到key对应的Entry所在的bucketIndex位置,然后从bucketIndex位置的Entry链表的头部开始向链尾遍历,如果遍历的Entry对象的hash值与key的hash值相等,Entry对象的key和参数Key的equals()返回true值,就认为找到了key所对应的对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值