HashMap数据结构分析

深入理解HashMap

HashMap的数据结构

1、JDK1.8之前,HashMap的数据结构是数组+链表的结构

2、JDK1.8开始,HashMap的数据结构为一个散列表(数组+链表+红黑树)

数组:查询快,但是增删操作效率慢

链表:增删快(只需修改前后节点的指向),但是查询慢(每次查询都会从头节点开始寻找)

为什么要引入红黑树?

答:当散列表元素达到一定的数量时,即HashMap中的元素数量,链表对于查询的效率会大幅度的下降,引入红黑树就是为了解决这个链表过长带来的效率问题

HashMap的参数

//散列表初始化容量大小,必须为2的幂,初始化为16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//散列表的最大容量,也必须为2的幂
static final int MAXIMUM_CAPACITY = 1 << 30;
//在构造函数未指定时,默认为改构造因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//链表转化为红黑树的条件之一,链表长度>8时
static final int TREEIFY_THRESHOLD = 8;
//链表转化为红黑树的条件之一,数组长度>64时
static final int MIN_TREEIFY_CAPACITY = 64;
//红黑树转化为链表的条件,数组长度小于等于6时
static final int UNTREEIFY_THRESHOLD = 6;

//HashMap内部维护的一个内部类Node
static class Node<K,V> implements Map.Entry<K,V> {
       final int hash;  //节点的hash值
       final K key;     //节点的key值
       V value;         //节点的value值
       Node<K,V> next;  //节点所指向下一个节点的指针
}

HashMap的构造函数

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);
       this.loadFactor = loadFactor;
       this.threshold = tableSizeFor(initialCapacity);
  }

我们可以看到对threshold进行了校验,也就是设置为2的幂数,通过tableSizeFor方法,目的是返回一个大于等于该值的2的幂次方数

static final int tableSizeFor(int cap) {
  //通过位运算
       int n = cap - 1;
       n |= n >>> 1;
       n |= n >>> 2;
       n |= n >>> 4;
       n |= n >>> 8;
       n |= n >>> 16;
       return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
  }

为什么要使用2的幂次方数来作为数组大小?

答:在使用寻址法key.hash & table.length -1的操作时,table.length-1后的操作,高位1变为0,低位全为1,如16的二进制为0001 0000,进行-1操作后为0000 1111,这样进行 & 运算时,每个hash桶位发生hash碰撞的概率都是一致的(减少同一个节点上的hash冲突,节点分布均匀)

HashMap的put()方法

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

首先会计算对应key的hash值,调用hash()方法,我们来看看该方法

static final int hash(Object key) {
       int h;
       return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
   //当key == null时,直接返回0,否则
   //调用key的hashCode方法得到散列值并赋值给局部变量h,对h进行无符号右移16位后^(异或)key的hash值
}

为什么通过寻址法定位到数组桶位,还是会发生hash冲突?

答:我们使用寻址法时,都会通过table.length-1的操作,将不定长的输入都转化为2的幂次数进行运算,(即相同的输出),自然会发生hash冲突

put方法调用了putVal方法,我们来对putVal方法进行分析

/*
   实现 Map.put 和相关方法。
   参数:
   hash – 密钥的散列
   key——钥匙
   value – 要放置的值
   onlyIfAbsent – 如果为真,则不更改现有值
   evict – 如果为 false,则表处于创建模式。
   返回值:
   以前的值,如果没有,则为 null
*/
//表,在第一次使用时初始化,并根据需要调整大小。 分配时,长度始终是 2 的幂。 (我们还在某些操作中容忍长度为零,以允许当前不需要的引导机制。)
transient Node<K,V>[] table;

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                  boolean evict) {
       Node<K,V>[] tab; Node<K,V> p; int n, i;
   //当前table未被使用过,没有进行初始化,第一次进行put操作
       if ((tab = table) == null || (n = tab.length) == 0)
           //进行扩容操作
           n = (tab = resize()).length;
  //当前桶位位空,则放入新节点,否则证明当前桶存在节点
       if ((p = tab[i = (n - 1) & hash]) == null)
           tab[i] = newNode(hash, key, value, null);
       else {
           Node<K,V> e; K k;
           if (p.hash == hash &&
              ((k = p.key) == key || (key != null && key.equals(k))))
            //如果当前节点的hash和传入的hash相同并且对应的key也相同
               //则将当前节点保存到临时节点e中
               e = p;
           else if (p instanceof TreeNode)
               //如果当前节点属于红黑树节点
               //则添加到红黑树的树节点中去
               e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
           else {
               for (int binCount = 0; ; ++binCount) {
                   //将当前节点指向的下一个节点保存到临时节点e中
                   if ((e = p.next) == null) {
                       //如果e为null,则添加到e所指向的节点中
                       p.next = newNode(hash, key, value, null);
                       //当前遍历链表的长度如果达到红黑树阈值,可能会进行树化
                       if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                           treeifyBin(tab, hash);
                       break;
                  }
                   //如果临时节点e的hash和传入的hash相同,并且key也相同时。则退出整个循环
                   if (e.hash == hash &&
                      ((k = e.key) == key || (key != null && key.equals(k))))
                       break;
                   p = e;
              }
          }
           if (e != null) { // existing mapping for key
               V oldValue = e.value;
               // onlyIfAbsent – 如果为真,则不更改现有值
               // onlyIfAbsent默认为false,代表在当前链表中找到相同key的节点就直接替换
               if (!onlyIfAbsent || oldValue == null)
                   //替换当前节点的value
                   e.value = value;
               afterNodeAccess(e);
               //返回旧值
               return oldValue;
          }
      }
  //修改次数+1
       ++modCount;
  //当前操作后的大小如果大于扩容阈值(容量*负载因子)
       if (++size > threshold)
           //则进行扩容
           resize();
       afterNodeInsertion(evict);
       return null;
  }

Put流程图

HashMap的resize()方法

 final Node<K,V>[] resize() {
    //oldTab持有当前数组的引用,即保存旧数组
       Node<K,V>[] oldTab = table;
    //将旧数组的容量赋值给oldCap,为null则为0
       int oldCap = (oldTab == null) ? 0 : oldTab.length;
    //进行扩容的数值标准赋值给oldThr
       int oldThr = threshold;
    //新数组的容量和负载因子都初始化为0
       int newCap, newThr = 0;
       if (oldCap > 0) {
           //如果当前数组容量大于0并且大于数组最大容量,即进行过初始化了
           if (oldCap >= MAXIMUM_CAPACITY) {
               //达到了最大值,无法进行扩容了
               threshold = Integer.MAX_VALUE;
               return oldTab;
          }
           //对当前数组的容量左移一位即扩容1倍,并赋值给newCap,扩容后的值必须小于最大容量
           //并且当前数组的容量大于等于默认初始化容量16
           else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
               //同时扩容的数值标准也得左移一位,即2*原数值
               newThr = oldThr << 1;
      }
       else if (oldThr > 0)
           //说明hashmap初始化的时候,传入了指定值(此时的oldThr经过位运算是一个2的幂次数了)
           //此时还没有初始化数组大小
           newCap = oldThr;
       else {  
           //不是扩容操作,没有传入指定的cap容量大小
           //此时数组容量为默认数组容量16
           newCap = DEFAULT_INITIAL_CAPACITY;
           //下次扩容的阈值为 16 * 0.75 =12
           newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
      }
       if (newThr == 0) {
          //计算新数组的扩容阈值
           float ft = (float)newCap * loadFactor;
           //当新数组容量小于最大容量 并且 扩容阈值小于最大容量 时,阈值为ft,否则则为Integer的最大值
           newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                    (int)ft : Integer.MAX_VALUE);
      }
    //将新数组的扩容阈值扶着给阈值
       threshold = newThr;
       @SuppressWarnings({"rawtypes","unchecked"})
       Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
       table = newTab;
    //当前数组不为空
       if (oldTab != null) {
           //对当前数组遍历进行迁移数据操作
           for (int j = 0; j < oldCap; ++j) {
               //定义一个临时节点e
               Node<K,V> e;
               //当前数组桶位不为空,将值赋给e
               if ((e = oldTab[j]) != null) {
                   //置当前桶位位空
                   oldTab[j] = null;
                   if (e.next == null)
                       //e.next为空表示当前桶位只有头节点,没有链表
                       //通过寻地址法计算索引,将临时节点e放入新数组的索引对应桶位
                       newTab[e.hash & (newCap - 1)] = e;
                   else if (e instanceof TreeNode)
                       //如果节点e位树节点,则进行树的相关操作
                      ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                   else { // preserve order
                       Node<K,V> loHead = null, loTail = null;
                       Node<K,V> hiHead = null, hiTail = null;
                       Node<K,V> 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;
  }

resize流程图

HashMap的remove()方法

remove里对返回的e进行判断,所要删除的key对应的桶位为null,则返回null,否则返回删除的value


public V remove(Object key) {
       Node<K,V> e;
       return (e = removeNode(hash(key), key, null, false, true)) == null ?
           null : e.value;
}

具体的删除过程由removeNode()实现

/*
实现 Map.remove 和相关方法。
参数:
hash – 密钥的散列
key——钥匙
value – 如果 matchValue 匹配的值,否则忽略
matchValue - 如果为真,则仅在值相等时删除
movable - 如果为false,则在删除时不移动其他节点
返回值:
节点,如果没有,则为 null
*/
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
//首先对数组进行非空判断,如果非空,再通过寻址法找到要删除的节点
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
//将当前节点指向null
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//如果当前节点和传入节点的hash相同并且key也相同
//则当前节点为要删除的节点
node = p;
//此处证明当前节点上存在链表
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
//如果当前节点是树节点,则通过树的相关方法进行删除
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
//此do.while循环对链表进行遍历,如果遍历到对应的节点则进行删除
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
//找到对应的节点则赋值给node节点
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
//现在执行删除操作
//matchValue为false,即!matchValue为true,则继续执行删除操作
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
//node == p则当前节点即为要删除的节点,将当前节点的下一个节点放在当前节点所在桶位
tab[index] = node.next;
else
//此处将node节点移除出链表
p.next = node.next;
//对修改次数+1
++modCount;
//K-V键值对数量-1
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}

HashMap的get()方法

public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//首先对数组进行非空判断,然后通过寻址法找到要删除的key
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
//如果传入的hash和当前节点(头节点)的hash相同,则返回当前节点
return first;
if ((e = first.next) != null) {
//如果头节点的next不为null,说明这是个链表
if (first instanceof TreeNode)
//判断当前节点是否为树节点
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
//对链表进行遍历,当遍历到对应节点的key,则返回对应节点
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}

 

JDK1.7中使用头插法引起的循环链表的问题

在这里插入图片描述

JDK1.7中,HashMap采用的是头插法

posted @ 2021-09-03 13:20  荒唐hh  阅读(249)  评论(0)    收藏  举报