實現固定大小的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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM