分享

HashMap详解

 丹枫无迹 2021-05-10

原文链接http:///2020/12/10/java%E5%9F%BA%E7%A1%80/%E9%9B%86%E5%90%88/HashMap%E8%AF%A6%E8%A7%A3/

HashMap详解

介绍

HashMap是在项目中使用的最多的Map,实现了Map接口,继承AbstractMap。基于哈希表的Map接口实现,不包含重复的键,一个键对应一个值,在HashMap存储的时候会将key、value作为一个整体Entry进行存储。

HashMap中会根据hash算法来计算key所对应的存储位置。

继承关系

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

在这里插入图片描述

数据结构

数组+链表+红黑树

默认采用数组+链表的方式存储元素,当元素出现哈希冲突时,HashMap使用链地址法来解决hash冲突,会存储在该位置的链表中。当链表中元素个数超过8个时,会尝试将链表转为红黑树存储。但是在转换前,会判断一次当前数组的长度,当数组长度大于64时才会处理,否则进行扩容操作

源码解析

重要参数

初始大小和加载因子

  • 初始大小用来规定哈希表数组的长度

  • 加载因子用来表示哈希表元素的填满程度,加载因子越大哈希表的空间利用率越高,但是哈希冲突的几率也会越大

静态常量

/**
* 默认初始容量16,必须为2的次幂
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
* 最大容量  最大为1<<30 即2^30
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
* 默认加载因子  0.75
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
* hash冲突链表节点个数大于8时,会转化为红黑树
*/
static final int TREEIFY_THRESHOLD = 8;

/**
* hash冲突时,当红黑树存储中节点少于6时,则转化为单链表存储
*/
static final int UNTREEIFY_THRESHOLD = 6;

/**
* 链表转为红黑树的最小表容量,如果没有达到该容量,将进行扩容
* 该值设置至小为4*TREEIFY_THRESHOLD
*/
static final int MIN_TREEIFY_CAPACITY = 64;

为什么容量一定要是2次幂

在计算数组下标时使用的是(n - 1) & hash来计算的,当n为2次幂时,n-1的低位将全是1,哈希值进行与操作时保证低位不变,最终得到的index结果,完全取决于key的hashCode的最后几位,从而保证分布均匀,效果等同于取模,且性能比取模高。

Node

HashMap中的元素都存储在Node数组中,看一下Node的结构

transient Node<K,V>[] table;

static class Node<K,V> implements Map.Entry<K,V> {
  // 该Node节点的hash值
    final int hash;
    final K key;
    V value;
  // 链表的下一个节点
    Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}

在这里插入图片描述

如果是链表,则使用的是Node存储(单向链表);如果是红黑树,则使用的是TreeNode

构造函数

无参构造函数
public HashMap() {
  this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
指定初始容量
public HashMap(int initialCapacity) {
  this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
指定初始容量和加载因子
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);
}

/**
* 返回大于等于cap最小的2的幂
*/
static final int tableSizeFor(int cap) {
  int n = cap - 1;
  // 右移一位,在进行按位或 保证了除最高位之外全是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;
}
传入map
public HashMap(Map<? extends K, ? extends V> m) {
  this.loadFactor = DEFAULT_LOAD_FACTOR;
  putMapEntries(m, false);
}

方法分析

put方法添加元素
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
/**
* 将key的hash值进行高16位和低16位异或操作,增加低16位的随机性,减少哈希冲突
*/
static final int hash(Object key) {
  int h;
  // 右移16位是为了使得hash值得高位参与运算
  return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}


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为null,resize()进行数组初始化
  if ((tab = table) == null || (n = tab.length) == 0)
    n = (tab = resize()).length;
  // 使用(n-1)&hash找到下标位置,如果当前没有元素,则创建Node对象,放到数组该位置
  if ((p = tab[i = (n - 1) & hash]) == null)
    tab[i] = newNode(hash, key, value, null);
  else { // 数组该位置已有值,hash冲突
    Node<K,V> e; K k;
    // 哈希值与key值都相同,则进行value值替代
    if (p.hash == hash &&
        ((k = p.key) == key || (key != null && key.equals(k))))
      e = p;
    else if (p instanceof TreeNode) // hash值相等,但是key不相等,且为红黑树
      e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
    else { // hash值相等,但是key不等,且为链表
      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  是否超过阈值,超过则进行链表转红黑树   表示添加之后的长度和TREEIFY_THRESHOLD进行比较
            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
      V oldValue = e.value;  // 进行
      if (!onlyIfAbsent || oldValue == null)
        e.value = value;
      afterNodeAccess(e);
      return oldValue;
    }
  }
  ++modCount;
  if (++size > threshold) // 元素个数大于新增阈值,进行resize()扩容
    resize();
  afterNodeInsertion(evict);
  return null;
}
扩容

当hashMap中的容量达到阈值时,就会开始扩容操作

final Node<K,V>[] resize() {
  Node<K,V>[] oldTab = table;// 当前的数组
  int oldCap = (oldTab == null) ? 0 : oldTab.length;
  int oldThr = threshold;
  int newCap, newThr = 0;
  if (oldCap > 0) {
    if (oldCap >= MAXIMUM_CAPACITY) { // 当前长度超过了最大容量,新增阈值为Integer.MAX_VALUE
      threshold = Integer.MAX_VALUE;
      return oldTab;
    }
    else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
             oldCap >= DEFAULT_INITIAL_CAPACITY) // 容量扩容为2倍且当新容量小于最大容量,原来的容量大于默认初始容量时,阈值扩容为2倍
      newThr = oldThr << 1; // double threshold
  }
  else if (oldThr > 0) // 此时oldCap<=0,指定了阈值,将阈值赋给容量 initial capacity was placed in threshold
    newCap = oldThr;
  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<K,V>[] newTab = (Node<K,V>[])new Node[newCap];// 扩容后的数组
  table = newTab;
  if (oldTab != null) { // 将原数组的数据放入到新数组中
    for (int j = 0; j < oldCap; ++j) {
      Node<K,V> e;
      if ((e = oldTab[j]) != null) {
        oldTab[j] = null;
        if (e.next == null) // 无后继节点,直接放入新数组计算的位置中
          newTab[e.hash & (newCap - 1)] = e;
        else if (e instanceof TreeNode) // 为红黑树节点,进行拆分
          ((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) { // 哈希值和原数组容量进行&操作,为0,则放入原数组的索引位置
              if (loTail == null)
                loHead = e;
              else
                loTail.next = e;
              loTail = e;
            }
            else { // 非0则放入原数组索引位置+原数组长度的新位置
              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;
}
红黑树转换

将单向链表转为双向链表,在遍历双向链表转为红黑树

final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    // 判断是否容量到达红黑树转换的最小容量
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        TreeNode<K,V> hd = null, tl = null; // hd指向首节点,tl指向尾结点
        do {
            TreeNode<K,V> p = replacementTreeNode(e, null); // 将链表转为红黑树
            if (tl == null) // 如果尾结点为null,说明还没有首节点
                hd = p; // 当前节点为首节点
            else { // 尾结点不为null,构造一个双向链表,将当前节点追加到双向链表的末尾
                p.prev = tl;
                tl.next = p;
            }
            tl = p;
        } while ((e = e.next) != null);
      // 将原本的单链表转化为一个节点类型为TreeNode的双向链表
        if ((tab[index] = hd) != null) // 把转换后的双向链表,替换数组原来位置上的单向链表
            hd.treeify(tab); // 将当前双向链表树形化
    }
}

双向链表转为红黑树

final void treeify(Node<K,V>[] tab) {
  TreeNode<K,V> root = null; //定义红黑树根节点
  for (TreeNode<K,V> x = this, next; x != null; x = next) { // 从TreeNode双向链表的头节点开始遍历
    next = (TreeNode<K,V>)x.next;
    x.left = x.right = null;
    if (root == null) { // 不存在根节点
      x.parent = null;
      x.red = false; // 红黑树根节点为黑色
      root = x; // 当前元素设为根节点
    }
    else { // 存在根节点
      K k = x.key;
      int h = x.hash;
      Class<?> kc = null;
      for (TreeNode<K,V> p = root;;) { //遍历红黑树
        int dir, ph;
        K pk = p.key;
        if ((ph = p.hash) > h) // 当前红黑树节点p的hash值大于双向链表节点x的哈希值
          dir = -1;
        else if (ph < h) // 当前红黑树节点p的hash值小于双向链表节点x的哈希值
          dir = 1;
        else if ((kc == null &&
                  (kc = comparableClassFor(k)) == null) ||
                 (dir = compareComparables(kc, k, pk)) == 0) // 两者相等,使用比较器比较
          dir = tieBreakOrder(k, pk);

        TreeNode<K,V> xp = p;
        if ((p = (dir <= 0) ? p.left : p.right) == null) { // 当前红黑树p为叶子节点
          x.parent = xp;
          if (dir <= 0) // 根据dir的值,确认是p的左节点还是右节点
            xp.left = x;
          else
            xp.right = x;
          root = balanceInsertion(root, x); // 进行平衡调整
          break;
        }
      }
    }
  }
  // 将TreeNode双向链表转换为红黑树之后,将根节点作为数组的当前位置
  moveRootToFront(tab, root);
}

将红黑树的根节点移动到数组的索引所在位置

static <K,V> void moveRootToFront(Node<K,V>[] tab, TreeNode<K,V> root) {
  int n;
  if (root != null && tab != null && (n = tab.length) > 0) {
    int index = (n - 1) & root.hash;
    TreeNode<K,V> first = (TreeNode<K,V>)tab[index]; // 数组当前索引的元素
    if (root != first) { // 根节点不是当前元素
      Node<K,V> rn;
      tab[index] = root; // 将根节点设置为当前索引的元素
      TreeNode<K,V> rp = root.prev;
      if ((rn = root.next) != null)
        ((TreeNode<K,V>)rn).prev = rp;
      if (rp != null)
        rp.next = rn;
      if (first != null)
        first.prev = root;
      root.next = first;
      root.prev = null;
    }
    assert checkInvariants(root);
  }
}
红黑树插入
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
  Class<?> kc = null;
  boolean searched = false;
  TreeNode<K,V> root = (parent != null) ? root() : this;
  for (TreeNode<K,V> p = root;;) {
    int dir, ph; K pk;
    if ((ph = p.hash) > h)
      dir = -1;
    else if (ph < h)
      dir = 1;
    else if ((pk = p.key) == k || (k != null && k.equals(pk)))
      return p;
    else if ((kc == null &&
              (kc = comparableClassFor(k)) == null) ||
             (dir = compareComparables(kc, k, pk)) == 0) {
      if (!searched) {
        TreeNode<K,V> q, ch;
        searched = true;
        if (((ch = p.left) != null &&
             (q = ch.find(h, k, kc)) != null) ||
            ((ch = p.right) != null &&
             (q = ch.find(h, k, kc)) != null))
          return q;
      }
      dir = tieBreakOrder(k, pk);
    }

    TreeNode<K,V> xp = p;
    if ((p = (dir <= 0) ? p.left : p.right) == null) {
      Node<K,V> xpn = xp.next;
      TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
      if (dir <= 0)
        xp.left = x;
      else
        xp.right = x;
      xp.next = x;
      x.parent = x.prev = xp;
      if (xpn != null)
        ((TreeNode<K,V>)xpn).prev = x;
      moveRootToFront(tab, balanceInsertion(root, x));
      return null;
    }
  }
}
红黑树拆分

在进行扩容操作时,会重新计算索引位置,拆分之后的红黑树需要判断个数,从而决定做去树化还是树化

final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
  TreeNode<K,V> b = this;
  // Relink into lo and hi lists, preserving order
  TreeNode<K,V> loHead = null, loTail = null; // 保存在原索引的红黑树
  TreeNode<K,V> hiHead = null, hiTail = null; // 保存在新索引的红黑树
  int lc = 0, hc = 0;
  for (TreeNode<K,V> e = b, next; e != null; e = next) { // 与链表操作基本一致
    next = (TreeNode<K,V>)e.next;
    e.next = null;
    if ((e.hash & bit) == 0) {
      if ((e.prev = loTail) == null)
        loHead = e;
      else
        loTail.next = e;
      loTail = e;
      ++lc;
    }
    else {
      if ((e.prev = hiTail) == null)
        hiHead = e;
      else
        hiTail.next = e;
      hiTail = e;
      ++hc;
    }
  }

  if (loHead != null) { // 原索引位置
    if (lc <= UNTREEIFY_THRESHOLD)
      tab[index] = loHead.untreeify(map);
    else {
      tab[index] = loHead;
      if (hiHead != null) // (else is already treeified)
        loHead.treeify(tab);
    }
  }
  if (hiHead != null) { // 新索引位置
    if (hc <= UNTREEIFY_THRESHOLD) // 红黑树节点小于去树化阈值,进行去树化操作
      tab[index + bit] = hiHead.untreeify(map);
    else { // 大于去树化阈值,进行树化操作
      tab[index + bit] = hiHead;
      if (loHead != null)
        hiHead.treeify(tab);
    }
  }
}
去树化操作
final Node<K,V> untreeify(HashMap<K,V> map) {
  Node<K,V> hd = null, tl = null;
  for (Node<K,V> q = this; q != null; q = q.next) {
    Node<K,V> p = map.replacementNode(q, null);
    if (tl == null)
      hd = p;
    else
      tl.next = p;
    tl = p;
  }
  return hd;
}

put操作的大致步骤如下:

  • 对key进行hash操作,找到索引位置,如果此时索引位置为null,直接插入
  • 如果此时索引位置不为null,说明出现了hash冲突,使用equals()比较key的值,如果存在与该key相同的值,则替换value
  • 如果不存在与该key相同的值,且此时存储结构为链表,则插入链表尾部,如果链表长度超过8个且数组长度大于64时,进行链表转红黑树
  • 当数组中数据达到阈值,则需要进行扩容,扩容时需要进行去树化
get方法获取元素
public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}
// hash为key的hash值
// key为所要查找的key对象
final Node<K,V> getNode(int hash, Object key) {
  Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
  // 数组不为null且该索引位置的头节点不为null
  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))))
      return first;
    // 头节点不匹配,且有后继节点
    if ((e = first.next) != null) {
      // 红黑树
      if (first instanceof TreeNode)
        // 红黑树查找
        return ((TreeNode<K,V>)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;
}

高并发问题

由于HashMap不是线程安全的,在高并发的情况下会出现问题,在插入时可能会出现问题

假如HashMap到达了扩容的临界点,此时有两个线程在同一时刻对HashMap进行put操作,两个线程都会进行扩容可能会形成链表环,使得下一次读操作出现死循环。

由于本身的博客百度没有收录,博客地址http://

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多