HashMap源码解析

成员变量:

默认初始化大小为16,必须为2的次幂(为了减少Hash碰撞,尽可能减少空间浪费,本文后面会进行讲解)

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

最大容量,必须是2的次幂

static final int MAXIMUM_CAPACITY = 1 << 30;

默认加载因子,当大小超过初始化大小加载因子是会进行扩容,也就是本文中160*0.75=12

static final float DEFAULT_LOAD_FACTOR = 0.75f;

树化阈值,当桶中元素超过8个时会将链表转为红黑树。值必须大于大于2且至少应为(通过查询资料,是时间和空间的一种权衡,认为这个值比较好。红黑树的平均查找长度是log(n),链表的平均查找长度为n/2。有大佬知道的希望提出)

static final int TREEIFY_THRESHOLD = 8;

还原阈值,当桶中元素降到6以下时会将红黑树转为链表。

static final int UNTREEIFY_THRESHOLD = 6;

最小树形化容量阈值:即 当哈希表中的容量 > 该值时,才允许树形化链表 (即 将链表 转换成红黑树).否则,若桶内元素太多时,则直接扩容,而不是树形化为了避免进行扩容、树形化选择的冲突,这个值不能小于 4 * TREEIFY_THRESHOLD

static final int MIN_TREEIFY_CAPACITY = 64;

存储数据的Node数组

transient Node<K,V>[] table;

部分构造函数:

//即使传入初始容量不是2的次幂。也会被转成大于该数的最小的2的次幂的那个数
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);
}
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;
}

方法解析:

1.根据key获取value:

  • HashMap是根据key的hash值决定key放入到哪个桶(bucket)中,通过 tab=[(n - 1) & hash]公式计算得出。其中tab是一个哈希表。

  • 为什么容量永远是2的次幂以及为什么是 tab=[(n - 1) & hash] 公式?

    首先与运算要比取模运算快;
    其次能保证索引值肯定在容量中,不会超出数组长度;
    最后(n - 1) & hash,当n为2次幂时,会满足一个公式:(n - 1) & hash = hash % n
    当n=8,hash为12时,12%8 = 4;1100&0111=0100 = 4;

  • 为什么通过(n-1)&hash来决定桶的索引?

右移16位可以保证高位特征也参与运算,n-1是为了更少的减少hash碰撞。
HashMap中的hash也做了处理就是右移16位,由于是无符号数,所以高位补0。n-1能保证最后一位一定为1。

public V get(Object key) {
      Node<K,V> e;
      return (e = getNode(hash(key), key)) == null ? null : e.value;
  }
static final int hash(Object key) {
      int h;
      return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  }
final Node<K,V> getNode(int hash, Object key) {
      Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
      if ((tab = table) != null && (n = tab.length) > 0 &&
          (first = tab[(n - 1) & hash]) != null) {
          // (n - 1) & hash,first就是这个下标位置存放的对象
          if (first.hash == hash &&
              ((k = first.key) == key || (key != null && key.equals(k))))
              //如果匹配成功,直接返回first
              return first;
              //否则就要在下标指向的红黑树或者链表中查找
          if ((e = first.next) != null) {
          //如果first是TreeNode对象,说明是红黑树
              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;
  }
final TreeNode<K,V> getTreeNode(int h, Object k) {
//定位到树的根节点,并调用其find方法
          return ((parent != null) ? root() : this).find(h, k, null);
      }
       
  final TreeNode<K,V> root() {
          for (TreeNode<K,V> r = this, p;;) {
              if ((p = r.parent) == null)
                  return r;
              r = p;
          }
      }
final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
          TreeNode<K,V> p = this; //从根节点开始遍历
          do {
              int ph, dir; K pk;
              TreeNode<K,V> pl = p.left, pr = p.right, q;    
              if ((ph = p.hash) > h)     //当前节点的hash值大于需要查找的hash,就在左子树中查找
                  p = pl;
              else if (ph < h)
                  p = pr;     //反之在右子树中进行查找
              else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                  return p;   //如果两个节点的hash值相等并且key值也相等,那么返回当前节点
              else if (pl == null)
                  p = pr;   //若左子树为空,就直接进行右子树的查找
              else if (pr == null)
                  p = pl;     //若右子树为空,那么在左子树中进行查找
                //若k的比较函数kc不为空,且k是可比较的,则根据k和pk的比较结果来决定继续在哪个子树中寻找
              else if ((kc != null ||  
                        (kc = comparableClassFor(k)) != null) &&
                        (dir = compareComparables(kc, k, pk)) != 0)
                  p = (dir < 0) ? pl : pr;
                //若k不可比,先在右子树中寻找
              else if ((q = pr.find(h, k, kc)) != null)
                  return q;
              else
              //再到左子树中进行查找
                  p = pl;
          } while (p != null);
          return null;
      }

2.插入数据:

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
//  如果onlyIfAbsent是true,则不会修改已存在key的值,所以HashMap会修改已存在键的值
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为空或者长度为0,则需要进行扩容,扩容方法在下方
    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))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)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
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

final Node<K,V>[] resize() {
    //获取扩容前的node数组以及长度
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    //扩容前的负载因子*初始化长度(阈值)
    int oldThr = threshold;
    int newCap, newThr = 0;
    //如果扩容前Node数组长度大于0
    if (oldCap > 0) {
        //如果扩容前数组大小已经达到1 << 30;则把阈值设为0x7fffffff即2^31-1
        //并且不会进行扩容
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
        //如果把扩容前数组大小左移一位(乘以2)小于最大容量并且扩容前数组大小大于等于初始化大小
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
                 //新的阈值也乘以2
            newThr = oldThr << 1; // double threshold
    }
    //如果扩容前阈值大于0,则新数组初始大小就被赋值为阈值
    else if (oldThr > 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);
    }
    //如果新阈值为0
    if (newThr == 0) {
        float ft = (float)newCap * loadFactor;
        //重新计算新阈值:如果新数组大小小于最大容量并且,阈值小于最大容量
        //那么使用如上计算值,否则使用 0x7fffffff即2^31-1
        newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                  (int)ft : Integer.MAX_VALUE);
    }
    //赋值阈值
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
    //新Node数组声明
        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)
                //并将值的hash与新数组长度-1.同前面的(n-1)&hash
                    newTab[e.hash & (newCap - 1)] = e;
                    //如果值是红黑树的节点 split方法在下方
                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) {
                            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;
}

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;
    //(e.hash & oldCap) == 0的放在原桶内
    //,(e.hash & oldCap) == 1的放到 j + oldCap 桶内。
    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;
}
//树化
final void treeify(Node<K,V>[] tab) {
    TreeNode<K,V> root = null;
    for (TreeNode<K,V> x = this, next; x != null; x = next) {
        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)
                    dir = -1; // 当前节点在节点p的左子树
                else if (ph < h)
                    dir = 1;// 当前节点在节点p的右子树
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0)
// 当前节点与节点p的hash值相等,
//当前节点key并没有实现Comparable接口或者实现Comparable接口
//并且与节点pcompareTo相等,该方法是为了保证在特殊情况下
//节点添加的一致性用于维持红黑树的平衡
                    dir = tieBreakOrder(k, pk);

                TreeNode<K,V> xp = p;
 根据dir判断添加位置也是节点p的左右节点,是否为空,若不为null在p的子树上进行下次循环
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    x.parent = xp;// 若添加位置为null,建立当前节点x与父节点xp之间的联系
                    if (dir <= 0)// 确定当前节点时xp的左节点还是右节点
                        xp.left = x;
                    else
                        xp.right = x;
                    root = balanceInsertion(root, x);// 对红黑是进行平衡操作并结束循环
                    break;
                }
            }
        }
    }
    moveRootToFront(tab, root);// 将红黑树根节点复位至数组头结点
}

//将红黑树转为链表
Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
    return new Node<>(p.hash, p.key, p.value, next);
}
Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
    LinkedHashMap.Entry<K,V> q = (LinkedHashMap.Entry<K,V>)p;
    LinkedHashMap.Entry<K,V> t =
        new LinkedHashMap.Entry<K,V>(q.hash, q.key, q.value, next);
    transferLinks(q, t);
    return t;
}
private void transferLinks(LinkedHashMap.Entry<K,V> src,
                           LinkedHashMap.Entry<K,V> dst) {
    LinkedHashMap.Entry<K,V> b = dst.before = src.before;
    LinkedHashMap.Entry<K,V> a = dst.after = src.after;
    if (b == null)
        head = dst;
    else
        b.after = dst;
    if (a == null)
        tail = dst;
    else
        a.before = dst;
}
//比较对象,确定插入左节点或是右节点
static int tieBreakOrder(Object a, Object b) {
    int d;
    if (a == null || b == null ||
        (d = a.getClass().getName().
         compareTo(b.getClass().getName())) == 0)
        d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
             -1 : 1);
    return d;
}
//红黑树平衡插入
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                            TreeNode<K,V> x) {
    x.red = true;
    for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
        //如果不存在父节点则颜色为黑
        if ((xp = x.parent) == null) {
            x.red = false;
            return x;
        }
        //如果节点颜色为黑色并且爷爷节点为空,返回根节点
        else if (!xp.red || (xpp = xp.parent) == null)
            return root;
        if (xp == (xppl = xpp.left)) { //父节点为爷爷节点的左节点
        //当爷爷节点的右节点不为空并且为红色
        //父节点和叔父节点置为black,同时将爷爷节点置为red,
        //将爷爷节点设置为当前新增节点,循环继续调整。
            if ((xppr = xpp.right) != null && xppr.red) {
                xppr.red = false;
                xp.red = false;
                xpp.red = true;
                x = xpp;
            }
            //叔父节点为空或者为黑色
            else {
                //插入节点为父节点的右节点同时父节点是爷爷节点的左节点,则进行左旋
                if (x == xp.right) {
                    root = rotateLeft(root, x = xp);
                    xpp = (xp = x.parent) == null ? null : xp.parent;
                }
                if (xp != null) {
                    xp.red = false;
                    if (xpp != null) {
                        xpp.red = true;
                        root = rotateRight(root, xpp);
                    }
                }
            }
        }
        否则父节点为爷爷的右节点
        else {
            if (xppl != null && xppl.red) {
                xppl.red = false;
                xp.red = false;
                xpp.red = true;
                x = xpp;
            }
            else {
                if (x == xp.left) {
                    root = rotateRight(root, x = xp);
                    xpp = (xp = x.parent) == null ? null : xp.parent;
                }
                if (xp != null) {
                    xp.red = false;
                    if (xpp != null) {
                        xpp.red = true;
                        root = rotateLeft(root, xpp);
                    }
                }
            }
        }
    }
}
// 将红黑树根节点复位至数组头结点
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);
    }
}

3.删除:

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}
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) {
        Node<K,V> node = null, e; K k; V v;
        //前面是在得到想要删除的节点,类似查找方法
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        else if ((e = p.next) != null) {
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        //如果得到node并且满足相关要求
        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)
                tab[index] = node.next;
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

final void removeTreeNode(HashMap<K,V> map, Node<K,V>[] tab,
                          boolean movable) {
    int n;
    if (tab == null || (n = tab.length) == 0)
        return;
    int index = (n - 1) & hash;
    TreeNode<K,V> first = (TreeNode<K,V>)tab[index], root = first, rl;
    TreeNode<K,V> succ = (TreeNode<K,V>)next, pred = prev;
    if (pred == null)
        tab[index] = first = succ;
    else
        pred.next = succ;
    if (succ != null)
        succ.prev = pred;
    if (first == null)
        return;
    if (root.parent != null)
        root = root.root();
    if (root == null || root.right == null ||
        (rl = root.left) == null || rl.left == null) {
        tab[index] = first.untreeify(map);  // too small
        return;
    }
    TreeNode<K,V> p = this, pl = left, pr = right, replacement;
    if (pl != null && pr != null) {
        TreeNode<K,V> s = pr, sl;
        while ((sl = s.left) != null) // find successor
            s = sl;
        boolean c = s.red; s.red = p.red; p.red = c; // swap colors
        TreeNode<K,V> sr = s.right;
        TreeNode<K,V> pp = p.parent;
        if (s == pr) { // p was s's direct parent
            p.parent = s;
            s.right = p;
        }
        else {
            TreeNode<K,V> sp = s.parent;
            if ((p.parent = sp) != null) {
                if (s == sp.left)
                    sp.left = p;
                else
                    sp.right = p;
            }
            if ((s.right = pr) != null)
                pr.parent = s;
        }
        p.left = null;
        if ((p.right = sr) != null)
            sr.parent = p;
        if ((s.left = pl) != null)
            pl.parent = s;
        if ((s.parent = pp) == null)
            root = s;
        else if (p == pp.left)
            pp.left = s;
        else
            pp.right = s;
        if (sr != null)
            replacement = sr;
        else
            replacement = p;
    }
    else if (pl != null)
        replacement = pl;
    else if (pr != null)
        replacement = pr;
    else
        replacement = p;
    if (replacement != p) {
        TreeNode<K,V> pp = replacement.parent = p.parent;
        if (pp == null)
            root = replacement;
        else if (p == pp.left)
            pp.left = replacement;
        else
            pp.right = replacement;
        p.left = p.right = p.parent = null;
    }

    TreeNode<K,V> r = p.red ? root : balanceDeletion(root, replacement);

    if (replacement == p) {  // detach
        TreeNode<K,V> pp = p.parent;
        p.parent = null;
        if (pp != null) {
            if (p == pp.left)
                pp.left = null;
            else if (p == pp.right)
                pp.right = null;
        }
    }
    if (movable)
        moveRootToFront(tab, r);
}

可能理解的还是不够好,希望有些错误的地方各位大佬可以指出来,我会修改,以免误人子弟。。

可以加我微信公众号哈,大家一起学习、成长

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值