HashMap和LinkedHashMap源码阅读

HashMap和LinkedHashMap

1. HashMap

1.1 key值hash的计算

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

​ int - 4字节共32位,用高16位与低16进行异或运算,充分利用hashCode函数返回的int值,降低了hash冲突的概率

​ 默认容量16,计算table下标方法为 (16-1)& hash值,即取出hash值的低四位,16 - 1二进制表示为1111

1.2 put方法

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

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;  // 第一次插入数据,进行resize()初始化
    if ((p = tab[i = (n - 1) & hash]) == null) // 计算要放入的桶索引:(n - 1) & hash
        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; // 头节点key值与要插入的元素相同,equals和==双判断
        else if (p instanceof TreeNode) //如果头节点为TreeNode类型,进行红黑树的插入操作
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else { //该桶节点为普通链表类型
            for (int binCount = 0; ; ++binCount) { //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;  // 遇到key相同直接跳出循环,后面进行value覆盖处理
                p = e; //链表便利
            }
        }
      	// 发现与要插入Map元素key值相同的元素,覆盖旧值
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);  // LinkedHashMap进行方法重写,accessOrder为true时进行会将e元素放到双向链表的尾部
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold) //扩容判断,threshold值为扩容阈值(eg: 16 * 0.75 = 12)
        resize(); 
    afterNodeInsertion(evict); //LinkedHashMap会进行重写,可能会进行remove eldest元素
    return null;
}

1.3 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;
  if ((tab = table) != null && (n = tab.length) > 0 &&
      (first = tab[(n - 1) & hash]) != null) { //first获取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);  // 循环遍历链表,寻找key相同的节点
    }
  }
  return null;
}


public boolean containsKey(Object key) {
  return getNode(hash(key), key) != null;
}

1.4 resize()扩容方法

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) {
          	//MAXIMUM_CAPACITY(最大容量,2的30次方):a power of two <= 1<<30.
            if (oldCap >= MAXIMUM_CAPACITY) { 
                threshold = Integer.MAX_VALUE; //无法继续进行X2扩容,可插入的元素最大数目调整至Integer最大值
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && 
                     oldCap >= DEFAULT_INITIAL_CAPACITY)  // cap进行X2扩容
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr; //构造函数中指定loadfactor和初始cap
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY; //16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //12 = 16 * 0.75f
        }
        if (newThr == 0) { //构造函数中指定loadfactor和初始cap, 计算新的扩容阈值
            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) { //e为该桶下头节点
                    oldTab[j] = null;
                    if (e.next == null) //该桶只有一个元素
                        newTab[e.hash & (newCap - 1)] = e; //计算e节点在新容量下的对应的桶索引,修改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) { 
                              //e.hash & oldCap 如果为0说明:e.hash与newCap-1异或运算结果还是j
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else { 
                              //e.hash & oldCap 如果为1说明:e.hash与newCap-1异或运算结果不再是j,而是j+oldCap
                                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;
    }

2. LinkedHashMap(继承于HashMap)

image-20210902215417847

2.1构造方法

accessOrder – the ordering mode - true for access-order, false for insertion-order

Access-order: 表示访问过节点会放到双向链表的尾部

Insertion-order: 按插入顺序排列双向链表

public LinkedHashMap(int initialCapacity,
                         float loadFactor,
                         boolean accessOrder) {
        super(initialCapacity, loadFactor);
        this.accessOrder = accessOrder;
}

2.2 newNode函数

  • LinkedHashMap结构图:

    image-20210902220601866

//LinkedHashMap中Entry节点中加入before和after指针    
static class Entry<K,V> extends HashMap.Node<K,V> {
        Entry<K,V> before, after;
        Entry(int hash, K key, V value, Node<K,V> next) {
            super(hash, key, value, next);
        }
    }


Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
    LinkedHashMap.Entry<K,V> p =
      new LinkedHashMap.Entry<K,V>(hash, key, value, e);
    linkNodeLast(p); //将new的节点加入双向链表尾部
    return p;
}
// link at the end of list
private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
    LinkedHashMap.Entry<K,V> last = tail;
    tail = p; //Update tail为新建的节点p
    if (last == null)
      head = p;
    else {
      p.before = last;
      last.after = p;
    }
}

2.3 重写的方法

  • get方法

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

    accessOrder为true时,调用afterNodeAccess方法

  • afterNodeAccess(),访问过e节点后会调用该方法,将访问过的节点移动到尾部

    void afterNodeAccess(Node<K,V> e) { // move node to last
            LinkedHashMap.Entry<K,V> last;
            if (accessOrder && (last = tail) != e) {
                LinkedHashMap.Entry<K,V> p =
                    (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
                p.after = null;
                if (b == null)
                    head = a;
                else
                    b.after = a;
                if (a != null)
                    a.before = b;
                else
                    last = b;
                if (last == null)
                    head = p;
                else {
                    p.before = last;
                    last.after = p;
                }
                tail = p;
                ++modCount;
            }
        }
    
    
  • afterNodeInsertion方法,在插入元素后会进行调用,可能会移除头部的元素

    移除条件:removeEldestEntry方法进行重写,例如写为 return size() > 常量;在需要进行移除的时候返回true,默认返回false,不进行移除操作

        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);
            }
        }
    
    
    		protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
            return false;
        }
    
  • afterNodeRemoval方法,会在移除节点后进行调用,从链表中remove,unlink

        void afterNodeRemoval(Node<K,V> e) { // unlink
            LinkedHashMap.Entry<K,V> p =
                (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
            p.before = p.after = null;
            if (b == null)
                head = a;
            else
                b.after = a;
            if (a == null)
                tail = b;
            else
                a.before = b;
        }
    
    

3. LinkedHashMap实现LRU缓存

package edu.swjtu.lxd;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

public class LRU<K, V> extends LinkedHashMap<K, V> implements Map<K, V> {

    public static final long serialVersionUID = 1L;

    private int MAX_CACHE = 10;
    public LRU(int initialCapacity, float loadFactor, int maxCache) {
        super(initialCapacity, loadFactor, true);
        MAX_CACHE = maxCache;
    }
    public LRU(int maxCache) {
        super(16, 0.75f, true);
        MAX_CACHE = maxCache;
    }

    @Override
    protected boolean removeEldestEntry(Entry<K, V> eldest) { //重写方法
        return size() > MAX_CACHE;
    }

    public static void main(String[] args) {
        Random random = new Random();
        LRU<Integer, String> lruCache = new LRU<>(6);
        for(int i = 0; i < 10; i++) {
            lruCache.put(i + random.nextInt(10), "a" + i);
        }
        System.out.println(lruCache.size());
        System.out.println(lruCache);
    }
}

image-20210902223332435

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值