浅析:LinkedHashMap

LinkedHashMap浅析

LinkedHashMap的插入有序性

LinkedHashMap是HashMap的一个子类。有很多的方法多是直接继承父类。最主要的区别是LinkedHashMap实现了一个继承HashMap.Node的内部类Entry

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

可以看到内部定义了两个Entry bofore和after,很明显LinkedHashMap维护的是一个双向的链表。

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);
    // 将put的数据添加到链表尾部
    linkNodeLast(p);
    return p;
}
private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
    LinkedHashMap.Entry<K,V> last = tail;
    // 更新队尾元素
    tail = p;
    if (last == null)
        head = p;
    else {
        p.before = last;
        last.after = p;
    }
}

在LinkedHashMap并么有对put方法进行重写,但是重写了newNode方法这是很重要的。执行put方法后,父类的putVal()方法执行的是LinkedHashMap的newNode。在newNode中在创建完Entry后调用linkNodeLast方法对put的数据插入到链表尾部。可以看出,LinkedHashMap对于插入有序性的保证是依靠内部维护的一个双向链表实现的。

LinkedHashMap的访问顺序性

public LinkedHashMap(int initialCapacity, float loadFactor) {
    super(initialCapacity, loadFactor);
    accessOrder = false;
}

public LinkedHashMap(int initialCapacity) {
    super(initialCapacity);
    accessOrder = false;
}

public LinkedHashMap() {
    super();
    accessOrder = false;
}

public LinkedHashMap(int initialCapacity,
                         float loadFactor,
                         boolean accessOrder) {
        super(initialCapacity, loadFactor);
        this.accessOrder = accessOrder;
}
 The iteration ordering method for this linked hash map: true
 for access-order, false for insertion-order.

LinkedHashMap默认是插入有序性(accessOrder=false)的。accessOrder=true是访问有序的。由于LinkedHashMap没有重写HashMap的put方法,但是HashMap留了几个回调接口共其子类实现。

void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }

HashMap.putVal

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    …………
    afterNodeInsertion(evict);
    return null;
}

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

HashMap.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;
    // table不为空,且删除的元素存在
        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;
            // 判断index位置的p是否为要删除的元素(因为HashMap的数据结构为数组+链表,可能hash相同,但是所要删除的key不在链表开头)
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                // 判断p是否成长为红黑树结构
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    // 遍历index处的链表
                    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)))) {
				// 判断该节点是否为树节点,如果树节点则调用removeTreeNode方法
                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;
                // 去更改在LinkedHashMap中的值(解除node的链接)
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

LinkedHashMap.afterNdoeRemoval

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

LinkedHashMap.get

public V get(Object key) {
    Node<K,V> e;
    if ((e = getNode(hash(key), key)) == null)
        return null;
    // 如果是访问顺序,则在get后调用afterNodeAceess 去更改key的位置
   
    if (accessOrder)
        afterNodeAccess(e);
    return e.value;
}

LinkedHashMap.afterNodeAccess 如果访问

void afterNodeAccess(Node<K,V> e) { // move node to last
        LinkedHashMap.Entry<K,V> last;
        // get的key不能是尾节点,因为如果是尾节点就没必要调换顺序了(最近访问的在链表的最尾部)
    	// 同样如果put的key以及存在,那么也会调用该方法来改变顺序
        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;
        }
    }

采用LinkedHashMap对LRU的简单实现

public class LRUTest {
    private static int size = 5;
    public static void main(String[] args) {
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(size, 0.75f, true){
        	// 设置该缓存区为5个大小,超过5个大小则开始清理最少访问的
            @Override
            protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
                return this.size() > size;
            }
        };
        map.put("1", "1");
        map.put("2", "2");
        map.put("5", "5");
        map.put("3", "3");
        map.put("4", "4");
        System.out.println(map.toString());

        map.put("6", "6");
        System.out.println(map.toString());
        map.get("3");
        System.out.println(map.toString());
        map.put("7", "7");
        System.out.println(map.toString());
        map.get("5");
        System.out.println(map.toString());
    }
}
posted @ 2021-06-24 10:32  有间猫  阅读(60)  评论(0编辑  收藏  举报