在java中实现固定⼤⼩的hashMap 在java中实现固定⼤⼩的hashMap
创建⼀个固定⼤⼩的hashMap
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.
mysql下载libs包的网址//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;
}
}
使⽤
@Test
public void testMaxSizeMap(){
MaxSizeHashMap<String,String> map = new MaxSizeHashMap<>(10);
for(int i=0;i<100;i++){
map.put(""+i,""+i);
}
System.out.println(map.size());  //10  保留最后存⼊map的10个数据
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。