美文网首页
java的LinkedHashMap

java的LinkedHashMap

作者: 稀饭粥95 | 来源:发表于2018-08-28 15:16 被阅读3次

本文章环境为java8

使用

public class Main {
    public static void main(String[] args) {
        LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>(15,1,true);
        for(int i=0;i<10;i++){
            map.put("key"+i, i);
        }
        map.get("key3");
        for(String value:map.keySet()){
            System.out.println(value);
        }
    }

}

原理

accessOrder用来设置是否访问有限,遍历顺序是访问顺序。默认是false,遍历顺序是插入顺序。

public class LinkedHashMap<K,V>
    extends HashMap<K,V>
    implements Map<K,V>
{
/**
     * The iteration ordering method for this linked hash map: <tt>true</tt>
     * for access-order, <tt>false</tt> for insertion-order.
     *
     * @serial
*/
final boolean accessOrder;
}

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

put操作

继承于HashMap,具体如何实现不做介绍

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

afterNodeRemoval、afterNodeInsertion、afterNodeAccess

LinkedHashMap对HashMap的afterNodeRemoval、afterNodeInsertion、afterNodeAccess方法进行重写

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

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

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

removeEldestEntry

通过覆盖这个方法,加入一定的条件,满足条件返回true。当put进新的值方法返回true时,便移除该map中最老的键和值。

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

测试

public class Main {
    public static void main(String[] args) {
        
        LinkedHashMap<Integer,Integer> map = new LinkedHashMap<Integer,Integer>(16, 0.75f, true){
            public boolean  removeEldestEntry(java.util.Map.Entry<Integer, Integer> eldest){
                if(size() > 3){
                    return true;
                }
                return false;
            }
        };
        map.put(1, 1);
        map.put(2, 2);
        map.put(3, 3);
        System.out.println(map.size());
        map.put(4, 4);
        System.out.println(map.size());
    }

}

缓存的应用

lru指的是least recently use,通过LinkedHashMap可以将访问多的元素放在列表头部,尾部是一些不经常访问的元素,可以回收

基于LinkedHashMap的lru设计

作者:How_2_Play_Life
链接:https://www.jianshu.com/p/987a25f9d470
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

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

    private static final long serialVersionUID = 1L;

    public LRU(int initialCapacity,
             float loadFactor,
                        boolean accessOrder) {
        super(initialCapacity, loadFactor, accessOrder);
    }

    /** 
     * @description 重写LinkedHashMap中的removeEldestEntry方法,当LRU中元素多余6个时,
     *              删除最不经常使用的元素
     * @author rico       
     * @created 2017年5月12日 上午11:32:51      
     * @param eldest
     * @return     
     * @see java.util.LinkedHashMap#removeEldestEntry(java.util.Map.Entry)     
     */  
    @Override
    protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
        // TODO Auto-generated method stub
        if(size() > 6){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {

        LRU<Character, Integer> lru = new LRU<Character, Integer>(
                16, 0.75f, true);

        String s = "abcdefghijkl";
        for (int i = 0; i < s.length(); i++) {
            lru.put(s.charAt(i), i);
        }
        System.out.println("LRU中key为h的Entry的值为: " + lru.get('h'));
        System.out.println("LRU的大小 :" + lru.size());
        System.out.println("LRU :" + lru);
    }
}

相关文章

网友评论

      本文标题:java的LinkedHashMap

      本文链接:https://www.haomeiwen.com/subject/rexqwftx.html