java 有限队列,容纳Java中最后N个元素的大小有限队列

A very simple & quick question on Java libraries: is there a ready-made class that implements a Queue with a fixed maximum size - i.e. it always allows addition of elements, but it will silently remove head elements to accomodate space for newly added elements.

Of course, it's trivial to implement it manually:

import java.util.LinkedList;

public class LimitedQueue extends LinkedList {

private int limit;

public LimitedQueue(int limit) {

this.limit = limit;

}

@Override

public boolean add(E o) {

super.add(o);

while (size() > limit) { super.remove(); }

return true;

}

}

As far as I see, there's no standard implementation in Java stdlibs, but may be there's one in Apache Commons or something like that?

解决方案

Apache commons collections 4 has a CircularFifoQueue<> which is what you are looking for. Quoting the javadoc:

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.

import java.util.Queue;

import org.apache.commons.collections4.queue.CircularFifoQueue;

Queue fifo = new CircularFifoQueue(2);

fifo.add(1);

fifo.add(2);

fifo.add(3);

System.out.println(fifo);

// Observe the result:

// [2, 3]

If you are using an older version of the Apache commons collections (3.x), you can use the CircularFifoBuffer which is basically the same thing without generics.

Update: updated answer following release of commons collections version 4 that supports generics.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值