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.
例如:
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 */
最佳答案
拿LinkedHashMap作为基类并重写其 removeEldestEntry
方法,如该方法的示例使用中所述。
关于java - 使用 Java 中的映射实现的队列数据结构,大小限制为 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13302635/