简体   繁体   English

在add()上丢失最旧元素的集合

[英]Collection that loses oldest elements on add()

I'm looking for a Java class that implements Collection and loses oldest elements when I add() a new one, if total number of elements is bigger than X. Does it exist or I have to implement it myself? 我正在寻找一个实现Collection的Java类,当我add()一个新的元素时,如果元素的总数大于X,它会丢失最旧的元素。它是否存在或者我必须自己实现它?

I need a thread-safe one. 我需要一个线程安全的。

Apart from Linkedhasmap if you are looking for list type solution, Google guava has EvictingQueue . 除了Linkedhasmap,如果您正在寻找列表类型解决方案,谷歌番石榴有EvictingQueue And for thread safety you must wrap it in a synchronized wrapper ( Queues#synchronizedQueue ). 对于线程安全,您必须将其包装在同步包装器中( Queues#synchronizedQueue )。

EvictingQueue<String> q = EvictingQueue.create(3);
Queue<String> syncQ =  Queues.synchronizedQueue(q);
syncQ.add("one");
syncQ.add("two");
syncQ.add("three");
syncQ.add("four");
System.out.println(q); // Prints [two, three, four]

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its CircularFifoQueue是一个先进先出队列,具有固定大小的替换它的队列
oldest element if it is full. 最古老的元素,如果它已满。

You can use the LinkedHashMap to do precisely that, quoting the Javadoc: 你可以使用LinkedHashMap来做到这一点,引用Javadoc:

// Sample use: this override will allow the map to grow up to 100 entries and then delete the 
// eldest entry each time a new entry is added, maintaining a steady state of 100 entries.

 private static final int MAX_ENTRIES = 100;

 protected boolean removeEldestEntry(Map.Entry eldest) {
    return size() > MAX_ENTRIES;
 }

for thread safe-ness you can wrap it using Collections.synchronizedmap() . 对于线程安全,您可以使用Collections.synchronizedmap()包装它。

I've used EvictingQueue added at v.15 of Google Guava to implement Moving Average functionality in the past. 我已经使用了Google Guava第15版添加的EvictingQueue来实现移动平均功能。

It is not thread-safe though. 但它不是线程安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM