HashMap(jdk1.7)--底层实现原理

本文详细剖析了HashMap的数据结构、实现原理及关键方法,包括put、get、数组扩容等过程,探讨了容量、负载因子对性能的影响。

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

数据结构

HashMap中的数据结构是数组+单向链表的组合,以键值对(key-value)的形式存储元素,通过put()和get()方法存储和获取元素

在这里插入图片描述

实现原理

成员变量
//默认初始容量
static final int DEFAULT_INITIAL_CAPACITY = 16;

//最大初始容量容量,2^30
static final int MAXIMUM_CAPACITY = 1 << 30;

//负载因子,默认0.75,负载因子越小,hash冲突率越低
static final float DEFAULT_LOAD_FACTOR = 0.75f;

//一个Entry类型的数组
transient Entry<K,V>[] table;

//HashMap实际存储的元素个数
transient int size;

//临界值(HashMap实际能存储的大小),公式为(threshold=capacity * loadFactor)
int threshold;

//负载因子
final float loadFactor;

//HashMap的结构被修改的次数--结构修改是指改变HashMap中映射的数量,或者以其他方式修改其内部结构
transient int modCount;

Entry的结构

static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        int hash;

        /**
         * Creates new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }

        public final K getKey() {
            return key;
        }

        public final V getValue() {
            return value;
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }

        public final int hashCode() {
            return (key==null   ? 0 : key.hashCode()) ^
                   (value==null ? 0 : value.hashCode());
        }

        public final String toString() {
            return getKey() + "=" + getValue();
        }

        /**
         * This method is invoked whenever the value in an entry is
         * overwritten by an invocation of put(k,v) for a key k that's already
         * in the HashMap.
         */
        void recordAccess(HashMap<K,V> m) {
        }

        /**
         * This method is invoked whenever the entry is
         * removed from the table.
         */
        void recordRemoval(HashMap<K,V> m) {
        }
    }

put过程分析

public V put(K key, V value) {
		//判断key值是否为null,如果为null调用putForNullKey(v)方法,见下方代码
		//key为null的元素,会被放到table[0],且table[0]的链表只有一个元素
        if (key == null)
            return putForNullKey(value);
        //计算key的hash值
        int hash = hash(key);
        //计算key要存放的桶的位置
        int i = indexFor(hash, table.length);
        //判断通的位置是否有元素
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            //如果有元素判断key是否相等(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);
        return null;
 }

private V putForNullKey(V value) {
		//将数组中的第0位上的Entry对象拿出来,判断是否为null(是否已经有元素)
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
        	//如果不为null,则将对象的value值进行覆盖,并将旧值返回。
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                //此方法是更新HashMap
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        //如果该位置上的链表上没有元素,则执行addEntry()方法
        //1参:hash值;2参:键;3参:值;4参:桶的位置
        addEntry(0, null, value, 0);
        return null;
    }

void addEntry(int hash, K key, V value, int bucketIndex) {
		//判断当前HashMap的大小是否达到扩容的阈值,并且要插入的数组位置已经有元素了,则进行扩容
        if ((size >= threshold) && (null != table[bucketIndex])) {
        	//扩容,后边说
            resize(2 * table.length);
            //扩容之后,重新计算key的hash值
            hash = (null != key) ? hash(key) : 0;
            //重新计算扩容后新的下标
            bucketIndex = indexFor(hash, table.length);
        }
		//见下方
        createEntry(hash, key, value, bucketIndex);
}

void createEntry(int hash, K key, V value, int bucketIndex) {
		//取出当前数组位置的链表
        Entry<K,V> e = table[bucketIndex];
        //创建一个Entry对象,把新对象放到链表的表头,并将新对象的next指向就只
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
}

数组扩容

在插入心智的时候,如果当前size已经达到了扩容的阈值,并且要插入的位置上已经有了元素,那么就会出发扩容,扩容后,数组的大小为原来的2倍

void resize(int newCapacity) {
		//获取当前数组
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        //如果当前数组的容量达到最大扩容容量
        if (oldCapacity == MAXIMUM_CAPACITY) {
        	//则将扩容阈值设置为Integer.MAX_VALUE并返回
            threshold = Integer.MAX_VALUE;
            return;
        }
		//创建一个新的数组,数组的容量为旧容量的2倍
        Entry[] newTable = new Entry[newCapacity];
        boolean oldAltHashing = useAltHashing;
         //计算是否需要对键重新进行哈希码的计算
        useAltHashing |= sun.misc.VM.isBooted() &&
                (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        boolean rehash = oldAltHashing ^ useAltHashing;
        /*
        *将原有所有的桶迁移至新的桶数组中
        *在迁移时,桶在桶数组中的绝对位置可能会发生改变
        *这就是为什么HashMap不能保证存储数据的顺序会发生变化的原因
        */
        transfer(newTable, rehash);
        table = newTable;
        //重新计算扩容阈值
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }

transfer方法

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);
                }
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

get过程分析

相对于put过程,get过程是非常简单的

  1. 根据key计算hash值
  2. 找到相应的数组下标:hash&(length-1)
  3. 遍历该数组位置处的链表,直到找到相等(==或equals)的key
 public V get(Object key) {
 		//判断key是否为null,如果为null则直接去table[0]的位置取,并返回
        if (key == null)
            return getForNullKey();
        //见下方
        Entry<K,V> entry = getEntry(key);

        return null == entry ? null : entry.getValue();
 }

 private V getForNullKey() {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
 }


final Entry<K,V> getEntry(Object key) {
		//获取当前key的hash
        int hash = (key == null) ? 0 : hash(key);
        //获取桶位置的链表,循环遍历链表上的值
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
             //如果不为空
            Object k;
            //如果key完全相同,则返回
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        //如果桶位置为空,则返回null
        return null;
 }

hash算法

我们可以看到在HashMap中要找到某个元素,需要根据key的hash值来求的对应数组中的位置。如何计算这个位置就是hash算法。

	/**
     * Returns index for hash code h.
     */
    static int indexFor(int h, int length) {
        return h & (length-1);
    }

性能问题

HashMap有两个参数影响其性能:初始容量和负载因子。都可以通过构造方法指定大小。
容量capacity是HashMap中的bucket哈希桶(Entry的链表)的数量,初始容量只是HashMap在创建时的容量,最大设置的初始容量为2^30,默认初始容量是16(必须为2的幂),为什么要规定容量要为2的幂呢?

HashMap的数据结构是数组+单链表的组合,我们洗完过的是元素存放的更均匀,最理想的效果是,Entry数组中的每个位置都有一个元素,这样查询的时候效率最该,不需要遍历单链表,也不需要通过equals去比较Key,而且空间利用率最大。那么如何计算才会分布最均匀呢?我们首先想到的就是%取余运算,哈希值%容量=bucketIndex

源码中是这么做的

static int indexFor(int h,int length){

//这里的h为key调用hashCode方法计算出来的hash值,length为目前的容量

return h&(length-1);

}

当容量是2的幂次方的时候,h&(length-1)=h%length,位运算的速度又比%运算快很多,所以规定容量是2的幂次方。因此也是为了解决hash冲突问题,也是为了解决采用2进制运算才规定容量是2的幂次方。

负载因子loadFactor是HashMap在其扩容之前可以达到多满的一种尺度,默认是0.75,尺度大小为(loadFactor*capacity)

扩容问题

数组扩容之后,原数组中的数据必须重新计算其在新数组中的桶的位置,并放进去,这个操作特别消耗性能,如果我们已经预知HashMap中元素的个数,那么预设初始容量能够有效的提高HashMap的性能。

线程安全问题

HashMap是线程不安全的,在多线程情况下直接使用HashMap会出现一些莫名其妙不可预料的问题。

小问题

HashMap所有集合类视图所返回的迭代器都是快速失败的(fail-fast),在迭代器创建之后,如果从结构上对映射进行修改,除非通过迭代器自身的remove或add方法,其他任何时间任何方式的修改,迭代器都会抛出ConcurrentModificationException。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

壹氿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值