LinkedHashMap的用法


LinkedHashMap,底層實現是在HashMap的基礎上,添加了雙向鏈表,可以根據訪問順序進行遍歷,從最少訪問到最頻繁訪問的升序訪問。DOC描述如下:

LinkedHashMap(int,float,boolean) create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently access-order . This kind of map is well-suited to building LRU caches.

普通的LinkedHashMap

public class LinkedHashMapTest {

    public static void main(String[] args) {
        //插入順序
        System.out.println("插入順序");
        accessByInsertOrder();
    }
    
    /**
     * new LinkedHashMap<>(),與普通的HashMap相似,按鍵值哈希進行遍歷
     */
    private static void accessByInsertOrder() {
        LinkedHashMap<String, Integer>  map = new LinkedHashMap<>();
        
        map.put("a", 1);
        map.put("b", 2);
        map.put("c", 3);
        map.put("a", 4);
        
        for(Entry<String, Integer> e : map.entrySet()) {
            System.out.println(e.getKey() + "-" +e.getValue());
        }
    }
}

輸出:

插入順序
a-4
b-2
c-3

按順序訪問進行遍歷

public class LinkedHashMapTest {

    public static void main(String[] args) {
        //訪問順序
        System.out.println("訪問順序");
        accessByAccessOrder();
    }
    
    /**
     * new LinkedHashMap<>(16, 0.75f, true),accessOrder=true,表示按訪問順序進行遍歷
     */
    private static void accessByAccessOrder() {
        LinkedHashMap<String, Integer>  map = new LinkedHashMap<>(16, 0.75f, true);
        
        map.put("a", 1);
        map.put("b", 2);
        map.put("c", 3);
        map.put("a", 4);
        
        for(Entry<String, Integer> e : map.entrySet()) {
            System.out.println(e.getKey() + "-" +e.getValue());
        }
    }
}

輸出:最新訪問的數據在后邊

訪問順序
b-2
c-3
a-4

LRU緩存

同上一篇文章

public class LinkedHashMapTest {

    public static void main(String[] args) {
        //LRU緩存
        System.out.println("LRU順序");
        LRUCache<String, Integer> cache = new LRUCache();
        for(int i = 0; i < 10; i++) {
            cache.put("a"+i, i+1);
        }
        cache.get("a0");
        cache.get("a1");
        cache.put("b", 10);
        
        for(Entry<String, Integer> e : cache.entrySet()) {
            System.out.println(e.getKey() + "-" +e.getValue());
        }
        
    }
    
    /**
     * 通過LinkedHashMap實現LRU緩存
     * @author Administrator
     *
     * @param <K>
     * @param <V>
     */
    static class LRUCache<K,V> extends LinkedHashMap<K,V>{
        
        static final int maxSize = 10;
        
        LRUCache(){
            super(16, 0.75f, true);
        }
        
        @Override
        protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
            return size() > maxSize;
        }
        
    }
}

輸出:最新訪問的數據在后邊,其中a2-3被移除緩存

LRU順序
a3-4
a4-5
a5-6
a6-7
a7-8
a8-9
a9-10
a0-1
a1-2
b-10

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM