HashMap底层

1、HashMap底层数据结构

JDK1.7的底层是 数组+链表;

JDK1.8之后 数组 + 链表 + 红黑树;

数组特点:具有随机访问的特点,能达到O(1)的时间复杂度,数组查询快,增删比较麻烦;

链表特点:与数组恰恰相反,链表的时间复杂度达到O(n),只能顺着节点依次的找下去,增删比较快,查询比较慢;

都知道 Map 是以键值对的形式存储的 num(key,value),key值不可以重复,假设下载有两个key一样被hash(key)作为同一个下标 i ,这是数组下标 i 只可以保存一个元素,此时链表就发挥作用了,加入链表来解决hash冲突,两个key会用next连接起来,当key被连接成一个链表时,每次只能从第一个Node开始寻找,查询就会很低,为了解决这个问题 JDK1.8之后引入了 红黑树 数据结构来解决这个问题。

1.1、为什么HashMap的负载因子是0.75

在HashMap中有个默认的 DEFAULT_LOAD_FACTOR 负载因子为 0.75;

假设我们将负载因子设置为1,那么HashMap的容量需要全部装满,才会允许扩容,HashMap的容量如果全部装满再扩容会伴随着大量的hash冲突,这时候put和get操作效率就回低下。

如果将负载因子设置为0.5,这时HashMap的容量达到50%就会进行扩容,这样虽然减少了hash冲突概率,但是会存在一半空间还没有被用到就扩容,会造成空间利用率低。

既然0.5和1都不行那么就取中间数0.75,显然不是这样的,而是根据一个数学公式(牛顿二项式)推理出一个数字,是0.693,而0.75是为了后期使用时为了方便计算而做出的。

HashMap的put操作(添加):

HashMap底层_第1张图片代码: 

//put操作
public V put(K key, V value) {
     return putVal(hash(key), key, value, false, true);
}

//计算key对象的hash值
static final int hash(Object key) { 
     int h;
     return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//进行与操作
}

//具体添加细节
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node[] tab; //创建数组
        Node p; //新节点
        int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length; //对数组进行初始化
        if ((p = tab[i = (n - 1) & hash]) == null) //(n - 1) & hash 求数组的下标,判断是否有元素。没有
            tab[i] = newNode(hash, key, value, null);  //直接放入
        else { //有元素
            Node e; 
            K k;
            //判断存储的节点是否已存在。
            //1.两个对象的hash值不同,一定不是同一个对象
            //2.hash值相同,两个对象也不一定相等
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p; //存储的节点的key的已存在,直接进行替换
            else if (p instanceof TreeNode) //存储的节点的key的不存在,判断是否为树节点(是不是已经转化为红黑树)
                e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
            else {//即不存在。也不是树节点,
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) { //直接找到链表的尾部,直接插入
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st 判断链表的长度是否大于可以转化为树结构的阈值
                            treeifyBin(tab, hash); //树化
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) //判断是否和插入对象相同
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key 存在映射的key,覆盖原值,将原值返回
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold) //hashmap的容量大于阈值
            resize(); //扩容
        afterNodeInsertion(evict);
        return null;
    }

第一种情况:当hash值相同,且key一样,说明要做value的替换,这个时候会走最下面的if语句,使用 e.value = value来替换元素;

第二种情况:如果key不相等,这个时候就是添加元素,当该列已经树化,那么直接调用 putTreeVal() 方法即可;

第三种情况:如果要添加元素,此时不是树的情况,就需要考虑链表的长度是否会造成树化,还有链表当中不存在这个key,如果大于8了,会变成红黑树调用treeifyBin()方法,如果链表hash值相同并且key也相同,就会进行替换。

resize()扩容:

HashMap底层_第2张图片

 代码:

	final Node[] resize() {
        Node[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //进行数组的扩容,长度为原来的2倍,阈值为原来的2倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
         **//进行数组的初始化,容量为默认值16,阈值为16*0.75**
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        //把原数组的元素调整到新数组中
        @SuppressWarnings({"rawtypes","unchecked"})
        Node[] newTab = (Node[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node e;
                //判断当前索引j的位置是否存在元素e
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    //判断 e.next是不是有值,简而言之,就是判断当前位置是否是树或者链表
                    if (e.next == null)
                    	//调整到新数组中
                        newTab[e.hash & (newCap - 1)] = e;
                    //如果是红黑树,进行树的拆分(具体不讲了)
                    else if (e instanceof TreeNode)
                        ((TreeNode)e).split(this, newTab, j, oldCap);
                    //如果是链表
                    else { // preserve order
                        Node loHead = null, loTail = null;
                        Node hiHead = null, hiTail = null;
                        Node next;
                        //遍历链表
                        do {
                            next = e.next;
                            //生成低位链表
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            //生成高位链表
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
						
						//将低位链表调整到新数组
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //将高位链表调整到新数组
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

HashMap的gut操作(查询):

public V get(Object key) {
      Node e;
      return (e = getNode(hash(key), key)) == null ? null : e.value;
}

//计算key的hash值
static final int hash(Object key) {
     int h;
     return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//具体实现
 final Node getNode(int hash, Object key) {
        Node[] tab; 
        Node first, e; 
        int n; 
        K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) { //数组不能为空并且当前索引位置的元素不能为空;如果为空,直接返回null值
            if (first.hash == hash && // always check first node//检查第一个元素,如果是,直接返回
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {//向下寻找
                if (first instanceof TreeNode)
                    return ((TreeNode)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

由上面的源码可知,,当通过Key获取值时,我们通过hash()计算出Key所对应的hash值,然后去调用getNode()真正的执行get操作。

HashMap为什么初始化大小是16:

当我们看hashMap的源码可知当新 put 一个数据时会进行计算位于table数组中的下标:int index =key.hashCode()&(length-1);每次扩容都是以2的整数次幂进行扩容。

因为是将二进制进行按位与,(16-1)是1111,末尾是1,这样可以保证计算后的index既可以是奇数也可以是偶数,并且只要传进来的key足够分散、均匀,那么 按位与 的时候index就会减少重复,这样就减少了hash的碰撞以及hashMap的查询效率。

你可能感兴趣的:(java)