HashMap浅析和LinkeHashMap

HashMap解析

  1. 无序的

  2. 数据结构为数组(Node数组)+链表+红黑树(jdk8开始)

  3. 非线程安全的

  4. 键值允许为null

  5. 一个key对应唯一的value

  6. 查询和删除都很快

  7. 能达到O(1)的平均时间复杂度

  8. 默认容量16

  9. 扩容因子0.75,,当键值对的数量大于 16 * 0.75 = 12 时,就会触发扩容。

  10. 链表长度大于8时转为红黑树,长度小于8时,红黑树转为链表

    因为数据量小时,链表查找速度比树更快,因为省去了一些平衡旋转的操作。

常量字段:

  1. 继承自AbstractMap
  2. 实现Map接口,Cloneable接口和序列化接口
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
	//默认的初始容量 1<<4 = 16 
	static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    /**
     * 最大容量 2^30
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

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

    /**
     * 当桶中(一个数组元素)的链表节点大于8个时,将其转为红黑树
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     *当桶中(一个数组元素)的链表节点小于等于6个时,将红黑树转为链表结构
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 在转变成树之前,还会有一次判断,只有总键值对数量大于 	   *64才会发生转换。这是为了避免在哈希表建立初期,多个键值      *对恰好被放入了同一个链表中而导致不必要的转化。
     */
    static final int MIN_TREEIFY_CAPACITY = 64;
    

其他字段:

   //Node数组,每个元素是一个Node节点,Node是该桶的单链表首节点
	transient Node<K,V>[] table;

    /**
     * 保存缓存的entrySet()
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * 当前键值对数量
     */
    transient int size;

    /**
     * 对HashMap修改的次数,如果单线程迭代遍历的时候执行了添加删除元素的操作,则会抛出ConcurrentModificationException异常
     */
    transient int modCount;
	 /**
     *  数组扩容的阈值(容量*负载因子)。
     */
  	int threshold;
    /**
     *  装载因子
     */
    final float loadFactor;

Node节点:

单链表结构的节点

 static class Node<K,V> implements Map.Entry<K,V> {
     	//即对key求hash后的hash值,每个桶中节点的hash值相同
        final int hash;
        final K key;
        V value;
     	//指向下个节点的引用
        Node<K,V> next;
    }

ThreeNode:

红黑树结构的树节点

因为集成了LinkedHashMap.Entry,因此具有双向链表的性质

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // 
        boolean red;//节点是否为红色
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

      

构造函数

默认构造:

public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;//初始化默认负载因子为0.75
    }

指定容量大小:

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);
    }

计算扩容阈值threshold:

该方法返回的是大于cap的最小的一个2^n的值

即,cap=3,则返回2^2=4

cap=5则返回2^3=8

cap=9~16 ,则返回2^4=16

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;
    }

put方法

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

首先调用hash()计算key的hash值:

  1. key为空,返回null
  2. 否则,让key.hashCode与其高16位异或获取hash值,hash冲突概率更小
   static final int hash(Object key) {
          int h;
          return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
      }

调用putVal插入键值对:

  final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                     boolean evict) {
          Node<K,V>[] tab; Node<K,V> p; int n, i;
      	//1.数组为空或数组长度为0 
          if ((tab = table) == null || (n = tab.length) == 0)		//1.1 进行初始化扩容
              n = (tab = resize()).length;
       //2. 通过(n-1) & hash计算元素应该放在哪个桶中,如果该桶为空
          if ((p = tab[i = (n - 1) & hash]) == null)
              //2.1 直接在该桶插入新的节点
              tab[i] = newNode(hash, key, value, null);
          else {
            //3. 该桶不为空  
              Node<K,V> e; K k;
              //3.1 如果hash值相同且key相同,说明该key已经存在,直接将第一个节点保存在e中,转到4
              if (p.hash == hash &&
                  ((k = p.key) == key || (key != null && key.equals(k))))
                  e = p;
              //3.2 如果首节点是红黑树节点
              else if (p instanceof TreeNode)
                  //插入树中
                  e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
              //3.3 如果是链表
              else {
                  //3.3.1 遍历链表
                  for (int binCount = 0; ; ++binCount) {
                      if ((e = p.next) == null) {
                          //到达尾部仍没有key,插入新的节点
                          p.next = newNode(hash, key, value, null);
                          if (binCount >= TREEIFY_THRESHOLD - 1) // 如果节点个数超过了8个,则将链表转为红黑树
                              treeifyBin(tab, hash);
                          break;
                      }
                      //如果key已存在,则停止遍历,此时的e就是要找的key,跳到4覆盖旧值
                      if (e.hash == hash &&
                          ((k = e.key) == key || (key != null && key.equals(k))))
                          break;
                      //继续下一个循环
                      p = e;
                  }
              }
              //4. e不为空,说明key已存在,要覆盖旧值后直接返回旧值
              if (e != null) { 
                  V oldValue = e.value;
                  if (!onlyIfAbsent || oldValue == null)
                      e.value = value;
                  afterNodeAccess(e);
                  return oldValue;
              }
          }
      //到达该位置,说明是新增节点,而不是修改节点,因此需要进行扩容判断
          ++modCount;
      	//键值对超过threshold,则进行扩容
          if (++size > threshold)
              resize();
      //空实现
          afterNodeInsertion(evict);
          return null;
      }

整个流程:

  1. table数组为空 -------> 进行扩容
  2. 数组不为空,指定hash值对应的槽位为空--------------->直接插入新节点,转到[7]
  3. 指定hash值槽位不为空,如果存在目标key,则直接覆盖旧值。转到6
  4. 否则,如果是红黑树,则插入树节点。转到 [6]
  5. 否则,就是链表,遍历链表,如果key不存在,则在尾部插入新节点,如果key存在,则覆盖旧值
  6. 如果有旧值(key已存在),则返回旧值
  7. 如果是新的key-value,则先判断是否需要扩容(++size > threshold)?,进行扩容后返回null。

扩容方法resize()

 final Node<K,V>[] resize() {
     	//获取旧table数组
        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)//且旧容量大于等于默认容量16
                //扩容阈值*2,增加一倍
                newThr = oldThr << 1; 
        }
        else if (oldThr > 0) 
            //如果使用了指定大小的构造函数,则扩容的新的容量为旧的扩容阈值
            newCap = oldThr;
        else {//使用了默认构造
            //新的容量为默认容量16
            newCap = DEFAULT_INITIAL_CAPACITY;
            //新的阈值为 16*0.75
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            //新的扩容阈值为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数组
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
     	//新的数组赋值给table
        table = newTab;
     //旧数组不为空时
        if (oldTab != null) {
            //遍历数组
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                //该桶首节点赋值存储到额,且节点不为空
                if ((e = oldTab[j]) != null) {
                    //清空旧的元素,方便GC
                    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;
                            //低位链表还放在原来的数组下标为j的位置中
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            //其余的放在数字下标为原下标+旧容量的位置中
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

扩容流程:

  1. 旧容量大于0时,且大于默认容量16,新容量为旧的两倍,新的扩容阈值为旧的两倍
  2. 如果使用带指定容量的构造函数,则新的容量为原扩容阈值,即在构造函数中根基指定容量计算的threshold。再根据新的容量计算新的扩容阈值
  3. 如果使用默认构造函数,则新容量为默认容量16 ,扩容阈值为16*0.75=12
  4. 构造新数组进行扩容

插入红黑树节点putTreeVal()

基本流程如下:

  1. 根据hash值和key从根节点开始查询,比当前节点的hash值小就在左子树查询,否则在右子树查询
  2. 如果找到了目标,即hash值和key都一样,则直接返回
  3. 如果没有找到目标key,则插入一个新节点,并做旋转平衡

链表转红黑树treeifyBin():

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)
            //如果数组为空或者长度小于64,则直接扩容,原因在属性中已讲
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {//否则进行树转换
            TreeNode<K,V> hd = null, tl = null;
            do {
                //循环将所有的节点变为TreeNode树节点
                TreeNode<K,V> p = replacementTreeNode(e, null);//就是new了一个TreeNode
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            //都转为树节点后,再将该桶转为红黑树
            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) {
                //next后移
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                if (root == null) {
                    //将第一个元素作为根节点
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {
                 // x即为当前访问链表中的元素
                K k = x.key;
                int h = x.hash;
                Class<?> kc = null;
        
                // 这里从root开始自顶向下遍历,每次都向树中插入一个节点
                    for (TreeNode<K,V> p = root;;) {
                        //dir 用于存储p.hash和x.hash的比较结果,-1代表在左子树查找,1代表在右子树查找
                        int dir, ph;
                        K pk = p.key;
                        if ((ph = p.hash) > h)
                            //要查找的key的hash小于当前节点
                            dir = -1;
                        else if (ph < h)
                            //要查找的key的hash大于当前节点
                            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;
                        //根据dir判断在左子树还是右子树查找
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            //x的hash值小于xp
                            if (dir <= 0)
                                //插入到xp的左子树
                                xp.left = x;
                            else
                                //插入插入到右子树
                                xp.right = x;
                            //插入后重新平衡
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
  	          }
  		  //把根节点移动到链表的头节点
            moveRootToFront(tab, root);
        }
  1. 第一次循环将首节点作为红黑树的根
  2. 后面每次都将原链表的元素通过hash值比较,连接到树节点的左子树或右子树,再进行平衡
  3. 最后将根节点移动到首节点

get

首先key的hash值,再调用getNode返回对应的节点

  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;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //1.首先判断首节点的hash是否与key的hash相等,
            if (first.hash == hash &&
                //且key为要找的key
                ((k = first.key) == key || (key != null && key.equals(k))))
                //直接返回第一个节点
                return first;
            //2.否则要遍历链表
            if ((e = first.next) != null) {
                //2.1如果是红黑树节点
                if (first instanceof TreeNode)
                    return //调用红黑树获取节点的方法获取
	                    ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                 //2.2 否则,循环遍历链表找到目标key   
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        //找到后返回目标节点
                        return e;
                } while ((e = e.next) != null);
            }
        }
     	//没找到返回null
        return null;
    }
  1. 根据key的hash值找到对应的桶
  2. 如果第一个元素就是目标key,则直接返回该节点
  3. 否则遍历首节点,如果是树节点,则调用红黑树的查找方法查找,否则按照链表的方式查询目标节点,找到就返回那个节点,否则返回null

remove

先计算key的hash值,再调用removeNode删除

  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;
            //1. 如果 首节点匹配,则直接将首节点保存到node
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            //2.否则遍历该链表或红黑树
            else if ((e = p.next) != null) {
                //2.1 如果是红黑树,则调用红黑树的查找方法找到待删除node
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    //2.2 如果是链表,则遍历链表查找待删除节点,保存在node
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            //3.此处若找到待删除节点,如果需要匹配值,就看待删除节点的值和传入的值是否相同,否则就不匹配
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                //3.1 如果是树节点
                if (node instanceof TreeNode)
                    //则调用红黑树的remove方法
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                //如果是首节点
                else if (node == p)
                    //则直接指向首节点的下一个节点
                    tab[index] = node.next;
                else
                    //否则让待删除节点的上一个节点p指向待删除节点的下一个节点
                    p.next = node.next;
                ++modCount;
                //减少键值对数
                --size;
                afterNodeRemoval(node);
                //返回删除的节点
                return node;
            }
        }
        return null;
    }

流程:

​ 设待删除节点为x

  1. 计算key的hash值,找到对应的桶

  2. 如果首节点就是 x,[entra] ,则让tab[index]指向x的下一个节点

  3. 否则从该节点遍历,如果是树节点,则调用红黑树的查找找到该节点,并按红黑树的remove进行删除,返回x

  4. 如果是链表,则按链表的方式找到x,[extra] ,让x的前一个节点指向x的后一个节点,返回x

    extra: 需要匹配值的话,必须值匹配才能删除,否则返回null;不需要匹配就直接删除

  5. 找不到就返回null

LinkeHashMap

  1. 继承了HashMap,因为拥有hashMap的所有特性,也是数组+链表+红黑树的实现
  2. 但是LinkedHashMap使用双向链表来维护,而不是单向链表
  3. 默认存储的顺序为插入的顺序
  4. 构造函数让accessOrder为true,则按照对元素访问的顺序存储

因为LinkedHashMap基于HashMap实现,在hashMap中,每次删除插入的最后都有个尾函数:

如:afterNodeAccess(e);afterNodeInsertion(evict);等,在HashMap中是空实现;

而LinkedHashMap只需要重写这些方法就可以实现自己的功能。

如每次插入节点后会调用:afterNodeInsertion

 void afterNodeInsertion(boolean evict) { // possibly remove eldest
        LinkedHashMap.Entry<K,V> first;
        if (evict && (first = head) != null && removeEldestEntry(first)) {
            K key = first.key;
            removeNode(hash(key), key, null, false, true);
        }
    }

其中removeEldestEntry默认返回false:

 protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
        return false;
    }

因此我们可以重写removeEldestEntry方法实现LRU置换算法,当元素个数大于容量时,就移除最久未访问的元素

 @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        // 当元素个数大于了缓存的容量, 就移除元素
        return size() > this.capacity;
    }
发布了75 篇原创文章 · 获赞 13 · 访问量 8369

猜你喜欢

转载自blog.csdn.net/weixin_43696529/article/details/105211625