hashmap原理详解

Hashmap 的底层: 数组+链表 (jdk7之前)
数组+链表+红黑树(jdk 8)


以jdk7为例说明:


HashMap map=new HashMap();
在实例化以后,底层创建了长度是16的一维数组Entry[] table
……已经执行过多次put……
map.put(key1,value1):
首先计算key1所在类的hashCode()计算key1哈希值,此哈希值经过某种算法计算以后,得到在entry数组中的位置。
如果此位置上的数据为空,此时的key1-value1添加成功。—情况1
如果此位置上的数据不为空,()意味着此位置上存在一个或者多个数据(以链表形式存在),比较key1和已存在的一个或者多个数据的哈希值:
如果key1的哈希值与已经存在的数据的哈希值都不相同,此时key1-value1添加成功。—情况2
如果key1的哈希值和已经存在的某个数据key2-value2的哈希值相同,继续比较,调用key1的equals(key2)方法,比较:
如果equals()返回false:此时的key1-value1。—情况3
如果equals()返回true:使用value1替换value2.

关于情况2和情况3的 此时key1-value1和原来的数据以链表的方式存储
在不断的添加过程中,会涉及到扩容问题,默认的扩容原来的2 倍,并将原来的数据复制过来。
在这里插入图片描述

jDK8相较于jdk7的底层的方面的区别:


new HashMap()底层没有创建一个长度为16的数组
jdk 8 底层的数据是:Node[],而非Entry[]
首次调用Put方法时,底层创建长度为16的数组
jdk7的底层结构只有:数组+链表。jdk8中底层结构:数组+链表+红黑树
当数组的某一个索引位置上的元素以链表的形式存在的数据个数>8,且当前数组的长度>64时,此时的索引位置上的所有数据改为使用红黑树存储。

变量的介绍
在这里插入图片描述


具体代码:jdk7

调用空参构造函数HashMap


/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}

进一步:调用HashMap(int initialCapacity, float loadFactor)


    /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     */
    transient Entry<K,V>[] table;

/**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive

     * 传过来的参数:initialCapacity=16  loadFactor=0.75
     */
    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
        int capacity = 1;
        // 这里的capacity 的值为16
        while (capacity < initialCapacity)
            capacity <<= 1;
        //赋值加载因子
        this.loadFactor = loadFactor;
        //16*0.75=12 这个12 扩容的阀值 ---临界值
        threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        // 实例化Entry实体
        table = new Entry[capacity];
        useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        init();
    }

put方法介绍:


/**
     * 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.
     */
    public V put(K key, V value) {
        //先判断key值是否为空值
        if (key == null)
        	// 若为空值,则把value值控制放到table[0]或者table[0]的链表中
        	// 下面会接着介绍 putForNullKey()
            return putForNullKey(value);
        // 接着对key值进行hash得到哈希值
        int hash = hash(key);
        // 索引到该key值在数组中的位置
        int i = indexFor(hash, table.length);
        // 循环table[i] 的连表,找到改key-value对存放的地方。
        // 若e不等于null 进入循环体,若e等于null则进行addEntry()方法。
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            // 判断该table[i]链表的上的某个key的哈希值是否等于 要存储的key的哈希值 和 该key
            // 是否等于该table[i]链表的这个某个key值 若同时满足者进行更新该某个key对应的value值
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
		//保证并发访问时,若HashMap内部结构发生变化,快速响应失败
        modCount++; 
        //若e等于null则进行addEntry()方法。
        addEntry(hash, key, value, i);
        return null;
    }

接着介绍putForNullKey(value)方法:

 	/**
     * Offloaded version of put for null keys
     * 当key值为空的时候,调用该方法 把value值进行存在table[0]的链表中
     */
   
    private V putForNullKey(V value) {
    	// 循环table[0]链表,若链表不空,则进行判断e.key是否为空,若为空则进行更新老值
        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;
    }

addEntry(hash, key, value, i)方法的介绍


	 /**
     * Adds a new entry with the specified key, value and hash code to
     * the specified bucket.  It is the responsibility of this
     * method to resize the table if appropriate.
     *
     * Subclass overrides this to alter the behavior of put method.
     */
    void addEntry(int hash, K key, V value, int bucketIndex) {
    	//这里的意思是先判断数组的里元素的个数是否大于临界值 12 
    	// 和数组的中要放的位置是否为空
    	// 若大于12 且放的位置不为空,则进行扩容
        if ((size >= threshold) && (null != table[bucketIndex])) {
        	//调用resize进行扩容 默认是原来的2倍
        	// 怎么扩容就这里不具体的将了!
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
		// 若不需要扩容,则进行添加entry
        createEntry(hash, key, value, bucketIndex);
    }

接着介绍createEntry()


   /**
     * Like addEntry except that this version is used when creating entries
     * as part of Map construction or "pseudo-construction" (cloning,
     * deserialization).  This version needn't worry about resizing the table.
     *
     * Subclass overrides this to alter the behavior of HashMap(Map),
     * clone, and readObject.
     */
    void createEntry(int hash, K key, V value, int bucketIndex) {
    	//原有的数据先取出来,然后作为新实例化的entry实体的next的entry
    	// 把新的新实例化的entry实体放到原有的数据的位置上去
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }

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) {
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值