Java LinkedHashMap removeEldestEntry()方法

java.util.LinkedHashMap.removeEldestEntry(Map.Entry eldest) 删除最旧的条目时返回true。

1 语法

private boolean removeEldestEntry(Map.Entry eldest)

2 参数

eldest :Map中最近插入的条目

3 返回值

如果要从Map中删除最旧的条目,则Map返回true;如果不打算删除或保留该条目,则返回false。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.LinkedHashMap.removeEldestEntry(Map.Entry eldest)方法的例子
 */
import java.util.*;

public class Demo {

    // Refers to the max size of the map following which
    // the removal takes place of the eldest entry
    private static final int MAX = 6;

    public static void main(String[] args)
    {

        // Creating the linked hashmap and implementing
        // removeEldestEntry() to MAX size
        LinkedHashMap<Integer, String> li_hash_map =
                new LinkedHashMap<Integer, String>() {
                    protected boolean removeEldestEntry(Map.Entry<Integer, String> eldest)
                    {
                        return size() > MAX;
                    }
                };
        // Adding elements using put()
        li_hash_map.put(0, "Welcome");
        li_hash_map.put(1, "To");
        li_hash_map.put(2, "The");
        li_hash_map.put(3, "World");
        li_hash_map.put(4, "Of");
        li_hash_map.put(5, "yiidian");

        System.out.println("" + li_hash_map);

        // Adding more elements
        li_hash_map.put(6, "yiidian.com");

        // Displying the map after adding one more element
        System.out.println("" + li_hash_map);

        // Adding more elements
        li_hash_map.put(7, "Hello");

        // Displying the map after adding one more element
        System.out.println("" + li_hash_map);
    }
}

输出结果为:

{0=Welcome, 1=To, 2=The, 3=World, 4=Of, 5=yiidian}
{1=To, 2=The, 3=World, 4=Of, 5=yiidian, 6=yiidian.com}
{2=The, 3=World, 4=Of, 5=yiidian, 6=yiidian.com, 7=Hello}

热门文章

优秀文章