我有一个
Java中的哈希映射,我需要限制其大小(50000的顺序).但我应该只删除最旧的项目.项的时间戳存储在条目对象的字段中:
Map<String,MyModel> snapshot = new HashMap<>();
和
public class MyModel { private ZonedDateTime createdAt; // other fields... }
我还按时间戳顺序将它们插入到地图中.
解决方法
HashMap没有“最老的”,它没有“第一”,它没有订单.
另一方面,LinkedHashMap就是为此设计的,它在条目之间维护一个双向链表,因此保持它们的插入顺序,它还提供了一个removeEldestEntry
方法:
public static void main(final String args[]) throws Exception { final int maxSize = 4; final LinkedHashMap<String,String> cache = new LinkedHashMap<String,String>() { @Override protected boolean removeEldestEntry(final Map.Entry eldest) { return size() > maxSize; } }; cache.put("A","A"); System.out.println(cache); cache.put("B","A"); System.out.println(cache); cache.put("C","A"); System.out.println(cache); cache.put("D","A"); System.out.println(cache); cache.put("E","A"); System.out.println(cache); cache.put("F","A"); System.out.println(cache); cache.put("G","A"); }
输出:
{A=A} {A=A,B=A} {A=A,B=A,C=A} {A=A,C=A,D=A} {B=A,D=A,E=A} {C=A,E=A,F=A}
大健康警告
Note that this implementation is not
synchronized
. If multiple threads access a linked hash map concurrently,and at least one of the threads modifies the map structurally,it must besynchronized
externally. This is typically accomplished bysynchronizing
on some object that naturally encapsulates the map. If no such object exists,the map should be “wrapped” using theCollections.synchronizedMap
method. This is best done at creation time,to prevent accidental unsynchronized access to the map:
Map m = Collections.synchronizedMap(new LinkedHashMap(...));