美文网首页
HashMap详解

HashMap详解

作者: Tancent | 来源:发表于2018-09-16 16:12 被阅读0次

问题导入:

 HashMap底层数据结构,如何处理hash冲突,为何HashMap的大小要设置为2的n次幂,为什么IndexFor方法里,需要hash&length-1,为什么HashMap允许null值,resize()过程,多线程下resize为什么会出现死循环?

1. HashMap的底层数据结构

         Hash采用的是链地址法(数组+链表)解决hash冲突问题(无外乎在取值和存值的时候,key会不会冲突),其中在hashMap内部定义了一个静态的内部类Entry,Entry包含key,value,next。

2.初始化HashMap

    分为两种情况,利用a.自定义的初始化的容量,b.利用HashMap内部定义的长度DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16默认是16,利用默认的长度就是创建一个Entry[] table = new Entry[DEFAULT_INITIAL_CAPACITY ];我们重点讲解的是第一种情况,随机定义一个初始化的容量,

public HashMap(int initialCapacity, float loadFactor) {

        int capacity = 1;//默认都是从1开始,位移,达到所有的容量都是2的n次幂

        while (capacity < initialCapacity)

            capacity <<= 1;//左移1位

        this.loadFactor = loadFactor;

        threshold = (int)(capacity * loadFactor);//阈值

        table = new Entry[capacity];//生成table数组

        init();

    }

注意table初始大小并不是构造函数中的initialCapacity!!

而是 >= initialCapacity的2的n次幂

引入新的问题:为什么这么设计数组的长度2的n次幂:其实为了更好的解决hash冲突

3. HashMap的存取

  从  get(key), put(key,value)入手,这两个容易发生hash冲突的地方,冲突主要是key的定位

存储时:

 int hash = hash(key.hashCode());//先计算key的hashCode,然后再hash

 int i = indexFor(hash, table.length);//定位到具体的table数组中

取值时:

 int hash = hash(key.hashCode());//先计算key的hashCode,然后再hash

 int i = indexFor(hash, table.length);//定位到具体的table数组中

 Entry[i];

3.1 put(key,value)的详解

      当存入值的时候,先计算key的hashCode,然后再hash,然后通过indexFor()定位到具体的table数组中,这时候出现当多个key定位到数组的同一个位置,先遍历该位置上的链表,判断有没有key相同,如果有的话,更新对应key的value,如果没有插入到头节点

public V put(K key, V value) {

        if (key == null)

      returnputForNullKey(value);//放入null值的时候,null总是放在数组的第一个链表中

        int hash = hash(key.hashCode());

        int i = indexFor(hash, table.length);//定位table的位置

        //遍历链表

        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;       //如果key在链表中已存在,则替换为新value

                e.recordAccess(this);

                return oldValue;

            }

        }

        modCount++;

        addEntry(hash, key, value, i);

        return null;

    }

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); //参数e, 是Entry.next

    if (size++ >= threshold)

            resize(2 * table.length);    //如果size超过threshold,则扩充table大小,再散列

        //先加入值,再扩容,可能导致最后一次扩容的浪费(用不着了)

}

3.2 get(key)

 public V get(Object key) {

        if (key == null)

            return getForNullKey();//当key为null的时候

        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;

}

3.3 null的存取

null key总是存放在Entry[]数组的第一个元素。

   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;

    }

    private V getForNullKey() {

        for (Entry<K,V> e = table[0]; e != null; e = e.next) {

            if (e.key == null)

                return e.value;

        }

        return null;

}

3.4确定table数组的位置

    static int indexFor(int h, int length) {

        return h & (length-1);

    }

按位取并,作用上相当于取模mod或者取余%。

因为hashMap容量的变化,我们总是将容量定位>=initCapacity的2的次幂,所以length-1,则每个位置上都是1,这样的与运算,可以保证均匀定位

3.5 resize()重新扩容

void resize(int newCapacity) {//newCapacity的值是旧的capacity的值的2倍,保证容量一直是2的次幂

        Entry[] oldTable = table;

        int oldCapacity = oldTable.length;

        if (oldCapacity == MAXIMUM_CAPACITY) {

            threshold = Integer.MAX_VALUE;

            return;

        }

        Entry[] newTable = new Entry[newCapacity];//创建新的table数组

        transfer(newTable);//旧的hashMap到新的hashMap值的转移

        table = newTable;

        threshold = (int)(newCapacity * loadFactor);

    }

 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); //重新计算index

                    e.next = newTable[i];

                    newTable[i] = e;//头插法插到链表中

                    e = next;

                } while (e != null);

            }

        }

    }

4.多线程并发的情况

在并发的情况下容易出现死循环

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;//如果在线程一执行到第9行代码就被CPU调度挂起,去执行线程2,且线程2把上面代码都执行完毕

                    int i = indexFor(e.hash, newCapacity);

                    e.next = newTable[i];

                    newTable[i] = e;

                    e = next;

                } while (e != null);

            }

        }

    }

    https://www.jianshu.com/p/1e9cf0ac07f4

https://www.cnblogs.com/dongguacai/p/5599100.html

相关文章

网友评论

      本文标题:HashMap详解

      本文链接:https://www.haomeiwen.com/subject/gamxnftx.html