实现固定大小的hashMap(JAVA)

1、创建一个固定大小的hashMap

 1 import java.util.LinkedHashMap;
 2 import java.util.Map;
 3 
 4 public class MaxSizeHashMap<K, V> extends LinkedHashMap<K, V> {
 5     private final int maxSize;
 6 
 7     public MaxSizeHashMap(int maxSize) {
 8         this.maxSize = maxSize;
 9     }
10 
11 
12     //
13     //Returns true if this map should remove its eldest entry. 
14     //This method is invoked by put and putAll after inserting a new entry into the map. 
15     //It provides the implementor with the opportunity to remove the eldest entry each time a new 
16     //one is added. This is useful if the map represents a cache: 
17     //    it allows the map to reduce memory consumption by deleting stale entries. 
18     //
19     @Override
20     protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
21         return size() > maxSize;
22     }
23 }

2、使用固定大小的hashMap

     @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个数据
    }

参考地址

https://www.cnblogs.com/scottgu/p/4118428.html
https://blog.csdn.net/ClementAD/article/details/50596178

原文地址:https://www.cnblogs.com/kiko2014551511/p/11527169.html