欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JDK1.8源码解读——HashMap源码

程序员文章站 2022-06-04 19:29:24
...

从类的Doc文档注释中,我们可以得出HashMap的一些特性:
  1 无序 允许为null 非同步
  2 底层由哈希表实现
  3 初始容量和负载因子对HashMap的影响很大
成员变量:

   /**默认初始值,必须是二的倍数 */
   static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
   /** 最大容量 */
   static final int MAXIMUM_CAPACITY = 1 << 30;
   /**默认的负载因子 */
   static final float DEFAULT_LOAD_FACTOR = 0.75f;
   /**阈值,一个哈希桶被添加到TREEIFY_THRESHOLD个节点的时候,桶中的链表会被转化为红黑二叉树 */
   static final int TREEIFY_THRESHOLD = 8;
   /** 阈值,将红黑二叉树转化成链表(红黑二叉树为了保持平衡,要进行左旋,右旋,换色,消耗资源)*/
   static final int UNTREEIFY_THRESHOLD = 6;
   /**桶可能被树化为树形结构的最小容量*/
   static final int MIN_TREEIFY_CAPACITY = 64;

存储结构:
HashMap内部包含了一个Node类型的数组table,Node即为 JDK1.8之前的Entry

transient Node<K,V>[] table;
/**
* Basic hash bin node, used for most entries.  (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/
static class Node<K,V> implements Map.Entry<K,V> {
 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里存储的是键值对。包含四个字段,从next字段我们可以看出Node是一个链表。
即table数组中每个位置被当成一个桶,一个桶用来存放一个链表Node。
  HashMap使用拉链法来解决冲突(ThreadLocalMap则是采用线性探测法),同一个链表存放key的哈希值相同的Node
1 put方法(HashMap的核心):

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

hash后的key,key Value ,两个参数

首先,看一下hash方法

static final int hash(Object key) {
  int h;
  return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

结论:
  int 一共32位,这里作者将其分成前16位和后16位。取key的hashcode,与keyhashCode的高16位做异或。这里是将低16位与高16位做运算,得到的值实际上是高位和低位的结合,这就增加了随机性。在一定程度上减少了散列冲突的发生。这里hashCode是调用的Object中的hashCode,即引用对象的hashcode与其内存地址有关

/**
* Implements Map.put and related methods
*
* @param key的哈希值
* @param key 键
* @param value 要放入的值
* @param onlyIfAbsent true 则不改变现有值,默认是false
* @param evict 如果是false,则表处于创建模式,默认是true
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
             boolean evict) {
  Node<K,V>[] tab; Node<K,V> p; int n, i;
  if ((tab = table) == null || (n = tab.length) == 0)
      n = (tab = resize()).length;
 //如果散列表为null,则初始化散列表
  if ((p = tab[i = (n - 1) & hash]) == null)
      tab[i] = newNode(hash, key, value, null);
  //将对象放入散列表的时,默认初始容量是16,也就是说,要放到table数组的0-15的位置上,所以通过tab[i = (n - 1) & hash]来确定数组下标位置,n如果为奇数,则n-1为偶数,0与任何数的&运算都是0,会造成一部分的内存浪费(下标最后一位为0的位置存不会存值)
  //如果没有发生散列冲突,则直接将新建的Entry对象放入table数组中
  else {
      Node<K,V> e; K k;
      if (p.hash == hash &&
          ((k = p.key) == key || (key != null && key.equals(k))))
          e = p;
//如果发生了散列冲突,就先记录下发生冲突的Node
      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) {
          //如果遍历链表没有发现该此节点,就插入链表的尾部(尾插法,1.8之前都是头插法)
                  p.next = newNode(hash, key, value, null);
          //如果插入后链表长度大于8,则转换为红黑树
                  if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                      treeifyBin(tab, hash);
                  break;
              }
         //如果key在链表中已经存在,则退出循环
              if (e.hash == hash &&
                  ((k = e.key) == key || (key != null && key.equals(k))))
                  break;
              p = e;
          }
      }
   //如果key在链表中已经存在,则修改其原先的key值,并且返回老的值
      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;
}

2 resize()方法:是HashMap的扩容方法,新的容量是旧的容量的两倍,需要注意的是,扩容操作同样需要把 oldTable 的所有键值对重新插入 newTable 中,因此这一步是很费时的。

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) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            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;
        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) {
                                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;
    }

3 get方法

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

通过key计算哈希值,调用getNode()来获取对应的value

/**
 * Implements Map.get and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @return the node, or null if none
 */
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) {
    //判断计算出来的hash值是否在散列表上
 
        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;
}

4 remove方法:从此映射中删除指定键的映射(如果存在)

public V remove(Object key) {
   Node<K,V> e;
   return (e = removeNode(hash(key), key, null, false, true)) == null ?
       null : e.value;
}
通过key计算哈希值,调用removeNode()来删除节点

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) {
    //同get,判断计算出来的hash值是否在散列表上
       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);
           }
       }
   //不是在首位,就去红黑树或者链表中查找,如果可以找到就记录下来

       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;
      //找到了对应的节点,并且value值对应上了,那么就可以删除了,这里也分三种情况,在链表,在红黑树,在桶的首位
       }
   }
   return null;
}

参考资料:
jdk1.8源码
https://github.com/CyC2018/CS-Notes/blob/master/notes/Java 容器.md#hashmap
大牛博客
https://blog.csdn.net/qq_33256688/article/details/79938886
HashMap到底是插入链表头部还是尾部

相关标签: jdk Java