深入源码理解HashMap

HashMap概述

基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。(除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变。

hashMap的初始化

初始化代码

Map<String, Integer> map = new HashMap<String, Integer>();

内部执行
涉及到的属性:
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int DEFAULT_INITIAL_CAPACITY = 16;

public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }

next

涉及到的属性:
static final int MAXIMUM_CAPACITY = 1 << 30;

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

        // Find a power of 2 >= initialCapacity
        // 找到不大于initialCapacity的最大容积,或者说就是找到合适的"桶"的数量,而且得到的数量始终是2的n次方
        int capacity = 1;
        while (capacity < initialCapacity)
            capacity <<= 1;

        // 初始化负载因子
        this.loadFactor = loadFactor;

        // The next size value at which to resize (capacity * load factor).
        // 找到下一个需要被散列的临界值
        threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);

        // Entry是hashMap的一个内部类,实例化一个以容积为大小的Entry数组,这个table就是实际上用来存储key-value的
        table = new Entry[capacity];

        // 不太懂这句的意思,以后再探讨
        useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);

        // 为子类预留的扩展方法,在HashMap类中留空了
        init();
    }

hashMap的运行时(put,get)

作为一个应用者,暂时只关注常用的两个方法

public V put(K key, V value);

put操作步骤
1. 得到key
2. 通过hash函数得到hash值
3. 得到桶号
4. 存放key和value在桶内。

    /**
     * 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) {

        // 如果key==null,则调用putForNull,这个方法实际上就是此value放入了Entry数组的首位置,由于null的唯一性,Entry数组的首位置只能放置一个value对象
        if (key == null)
            return putForNullKey(value);

        // 根据key获取hash码
        int hash = hash(key);

        // 根据上一步的hash码和Entry数组的长度,即当前容积, 获取当前value应该放入的位置。
        int i = indexFor(hash, table.length);

        // 如果当前key之前已有对应的value,则进行替换操作,方法返回此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++;

        // 将映射添加到Entry数组之中
        addEntry(hash, key, value, i);
        return null;
    }
put方法中涉及到的几个方法
putForNullKey(value);
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;
    }
hash(key);

根据key的hashCode返回的hashCode,进行一系列的位运算,目的是使hashCode转化为二进制时10尽量分散

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

        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, table.length);

根据之前的hashCode 和 容积,得到当前value应该存放的位置
其实就是求余操作,利用位运算来提升效率。

static int indexFor(int h, int length) {
        return h & (length-1);
    }
addEntry(hash, key, value, i);
void addEntry(int hash, K key, V value, int bucketIndex) {
        // 如果当前entry的size大于临界值,且需要存储value的目标桶不为空,则进行散列操作,具体散列操作暂不做探讨
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }

        // 添加key-value的具体操作
        createEntry(hash, key, value, bucketIndex);
    }

public V get(Object key);

get操作步骤:
1. 得到key
2. 通过hash函数得到hash值
3. 得到桶号
4. 比较桶的内部元素是否与key相等,若都不相等,则没有找到。
5. 取出相等的记录的value。

    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        // 取到null对应的值
        if (key == null)
            return getForNullKey();

        // key对应的记录Entry
        Entry<K,V> entry = getEntry(key);

        // 返回最终的key对应的value
        return null == entry ? null : entry.getValue();
    }
getEntry(Object key)
final Entry<K,V> getEntry(Object key) {

        // 取得hash码
        int hash = (key == null) ? 0 : hash(key);

        // 在当前hash对应的桶中,在value链表上找到key对应的value,此处使用到了key的equals方法。
        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 != null && key.equals(k))))
                return e;
        }
        return null;
    }
entry.getValue();
public final V getValue() {
            return value;
        }

小结

  1. 要使用hashMap,使用者需要注意实现key的hashCode和equals方法
  2. hashMap支持key为null的情况
  3. hashMap不应在多线程中使用,若需要多线程环境下的hashMap,可采用实现了线程安全的ConcurrentHashMap
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值