Data Structure for Queue using Map Implementations in Java with Size limit of 5

强颜欢笑 提交于 2019-12-13 19:17:27

问题


I have map with some records. I want to restrict that map to only 5 elements and whenever a new element is added the first item should be removed and new element should be added in last position of map. Something similar to FIFO. Can anyone please suggest me a data structure to use or the solution itself.

E.g :

Map<String,String> map=new LinkedHashMap<String,String>(5);
for(int i=0;i<5;i++){
map.put(i+"",i+"");
}
map.put("5","5"); /* should remove map.get(0) and map.size will be still 5.Contents      would 1,2,3,4,5 */

回答1:


Take LinkedHashMap as the base class and override its removeEldestEntry method as described in the sample use of the method.



来源:https://stackoverflow.com/questions/13302635/data-structure-for-queue-using-map-implementations-in-java-with-size-limit-of-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!