首页 > 编程语言 > 详细

如何在JAVA中实现一个固定最大size的hashMap

时间:2014-11-24 13:30:42      阅读:240      评论:0      收藏:0      [点我收藏+]

如何在JAVA中实现一个固定最大size的hashMap

利用LinkedHashMap的removeEldestEntry方法,重载此方法使得这个map可以增长到最大size,之后每插入一条新的记录就会删除一条最老的记录。

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

public class MaxSizeHashMap<K, V> extends LinkedHashMap<K, V> {
    private final int maxSize;

    public MaxSizeHashMap(int maxSize) {
        this.maxSize = maxSize;
    }


    //
    //Returns true if this map should remove its eldest entry. 
    //This method is invoked by put and putAll after inserting a new entry into the map. 
    //It provides the implementor with the opportunity to remove the eldest entry each time a new 
    //one is added. This is useful if the map represents a cache: 
    //    it allows the map to reduce memory consumption by deleting stale entries. 
    //
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > maxSize;
    }
}

 

如何在JAVA中实现一个固定最大size的hashMap

原文:http://www.cnblogs.com/scottgu/p/4118428.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!