使用LinkedHashMap做最简单的LRU缓存

继承HashMap类,实现最简单的缓存:

package com.caiya.test;

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

/**
 * Created by caiya on 16/3/12.
 */
public class LRUCache<K, V> extends LinkedHashMap<K, V> {

    private int cacheSize;

    public LRUCache(int cacheSize){
        // 默认使用HashMap的默认值
        super(16, 0.75f, true);
        this.cacheSize = cacheSize;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > cacheSize;
    }

}

测试代码:

package com.caiya.test;

import com.alibaba.fastjson.JSONObject;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class AppTest 
    extends TestCase
{
    /**
     * Create the test case
     *
     * @param testName name of the test case
     */
    public AppTest( String testName )
    {
        super( testName );
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return new TestSuite( AppTest.class );
    }

    /**
     * Rigourous Test :-)
     */
    public void testApp()
    {
        LRUCache lruCache = new LRUCache(3);
        for(int i = 0; i<10; i++){
            lruCache.put("name" + i, "value" + i);
        }
        System.out.println("-----" + JSONObject.toJSONString(lruCache));
        lruCache.get("name8");
        lruCache.put("name10", "value10");
        System.out.println("=====" + JSONObject.toJSONString(lruCache));
    }

}

测试结果:

Connected to the target VM, address: '127.0.0.1:60604', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:60604', transport: 'socket'
-----{"name7":"value7","name8":"value8","name9":"value9"}
====={"name9":"value9","name8":"value8","name10":"name10"}
Process finished with exit code 0


你可能感兴趣的:(使用LinkedHashMap做最简单的LRU缓存)