Skip to content
标签
欢迎扫码关注公众号

LinkedHashMap 的自动删除功能

LinkedHashMap 除了值是有序的之外,还可以自动删除最前面保存的值。

LinkedHashMap 中有一个 removeEldestEntry 方法,如果这个方法返回 trueMap 中最前面添加的内容将被删除,它是在添加属性的 putputAll 方法被调用后自动调用的。

这个功能主要是用在缓存中,用来限定缓存的最大数量,以防止缓存无限制地增长。

设置方法就是覆写 removeEldestEntry 方法,代码如下:

java
package liujiajia.me.learn.java;

import com.sun.deploy.util.StringUtils;

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

/**
 * Created by liujiajia on 2018/3/19.
 */
public class Application {
    public static final int DEFAULT_CACHE_LIMIT = 10;

    private static final Map<String, Object> viewCreationCache = new LinkedHashMap<String, Object>(DEFAULT_CACHE_LIMIT, 0.75f, true)
    {
        @Override
        protected boolean removeEldestEntry(Map.Entry<String, Object> eldest) {
            if (size() > DEFAULT_CACHE_LIMIT) {
                viewCreationCache.remove(eldest.getKey());
                return true;
            } else {
                return false;
            }
        }
    };

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            viewCreationCache.put(String.valueOf(i), null);
            System.out.println(viewCreationCache.size());
            System.out.println(StringUtils.join(viewCreationCache.keySet(), ","));
        }
    }
}

执行结果:

java
1
0
2
0,1
3
0,1,2
4
0,1,2,3
5
0,1,2,3,4
6
0,1,2,3,4,5
7
0,1,2,3,4,5,6
8
0,1,2,3,4,5,6,7
9
0,1,2,3,4,5,6,7,8
10
0,1,2,3,4,5,6,7,8,9
10
1,2,3,4,5,6,7,8,9,10
10
2,3,4,5,6,7,8,9,10,11
10
3,4,5,6,7,8,9,10,11,12
10
4,5,6,7,8,9,10,11,12,13
10
5,6,7,8,9,10,11,12,13,14
10
6,7,8,9,10,11,12,13,14,15
10
7,8,9,10,11,12,13,14,15,16
10
8,9,10,11,12,13,14,15,16,17
10
9,10,11,12,13,14,15,16,17,18
10
10,11,12,13,14,15,16,17,18,19

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.