Java 中保存最后 N 个元素的大小受限队列 [英] Size-limited queue that holds last N elements in Java

查看:24
本文介绍了Java 中保存最后 N 个元素的大小受限队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个非常简单的 &关于 Java 库的快速问题:是否有一个现成的类实现具有固定最大大小的 Queue - 即它总是允许添加元素,但它会默默地删除头元素以容纳新的空间添加元素.

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<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;
    }
}

据我所知,Java 标准库中没有标准实现,但可能在 Apache Commons 或类似的东西中有一个?

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 有一个 CircularFifoQueue<> 这就是你要找的.引用 javadoc:

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

CircularFifoQueue 是一个具有固定大小的先进先出队列,如果已满则替换其最旧的元素.

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<Integer> fifo = new CircularFifoQueue<Integer>(2);
    fifo.add(1);
    fifo.add(2);
    fifo.add(3);
    System.out.println(fifo);

    // Observe the result: 
    // [2, 3]

如果您使用的是旧版本的 Apache 公共集合 (3.x),您可以使用 CircularFifoBuffer 基本上没有泛型是一样的.

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.

更新:在支持泛型的公共集合版本 4 发布后更新了答案.

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

这篇关于Java 中保存最后 N 个元素的大小受限队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆