Size-limited queue that holds last N elements in Java

本文探讨了如何在Java中实现一个有限大小的队列,并介绍了Apache Commons Collections库中的CircularFifoQueue类作为替代方案。通过示例代码展示了手动实现的方法,以及如何利用现有库来简化开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A very simple & quick question on Java libraries: is there a ready-made class that implements a Queuewith 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<E> extends LinkedList<E> {
    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?





47 down vote accepted
+50

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.

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

Update: updated answer following release of commons collections version 4


转载于:https://www.cnblogs.com/mewishu/p/4162858.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值