HashMap源码分析

HashMap是一种装载key-value的数据结构(字典)。

特点 

查询速度快

实现分析

如果采用链表结构直接存储,查询的时间复杂度为O(n),显然不能满足需要;我们都知道数组支持随机访问,通过索引index可以在O(1)的时间内定位元素。

关键问题

如何将key值与index关联上 :hash算法生成相应的hash值,并&上数组的长,

hash值重复

那么问题来了,再好的hash算法,也有可能生成相同的hash值,这种情况下不同的元素被映射到相同的位置上,直接覆盖以前的元素会造成数据的丢失,肯定是行不通的。

解决方法

数组的每个元素代表一个链表,当hash值重复时,直接将新的元素添加到链表上。

降低重复

如果hash之后重复的元素过多,导致其中某个链很长,会降低查询速度。

1.选择更有的hash算法

2.设置负载因子load factor,即保持数组一定的空闲度,通过牺牲一定的空间,提高查询的速度。HashMap采用load_factor = 0.75(当空间利用率超过75%时,对数组进行扩容)

HashMap采用数组+链表相结合

源码分析

public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable

HashMap类实现了Map接口,同时实现了Cloneable和Serializable以支持深度拷贝和序列化

核心属性

	//默认的数组容量,要求必须是2的次方MUST be a power of two
    static final int DEFAULT_INITIAL_CAPACITY = 16;

    //定义最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //负载因子,有利于降低重复概率
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    //存储数组,必要时可以扩容:即空间利用率超过0.75时
    transient Entry<K,V>[] table;

    //元素个数
    transient int size;

    //threshold = 容量(capacity) * 负载因子(loadFactor),当size > threshold 时对数组进行扩容
    int threshold;

    //负载因子
    final float loadFactor;
核心方法

1.hash函数,生成hash码

    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);
    }
2.生成数组索引(bucket)

       根据hash函数生成的hash码+数组长度

            bucketIndex = indexFor(hash, table.length);

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

    a.通过key生成hash码-->b.根据hash码+数组长度生成index-->c.然后根据index判断元素是否已经存在,如果存在直接返回,反之,调用addEntry方法进行保存。

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

4.查找元素

    如果key为空,获取默认空可以,然后调用getEntry(key)查询元素的

    public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);

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

     a.通过key生成hash码-->b.根据hash码+数组长度生成index,然后判断元素是否存在,如果存在返回,返回元素;反之,返回 null。

    final Entry<K,V> getEntry(Object key) {
        int hash = (key == null) ? 0 : hash(key);
        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;
    }

5.元素结构

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


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值