gpt4 book ai didi

java - 是否有任何实现 maxlen 的 java Deque,如 python collections.deque?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:59:35 26 4
gpt4 key购买 nike

Python 的 collections.deque有一个 maxlen 参数,这样

[...] the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. [...]

我一直在寻找一个实现 Deque interface 的类在 Java 中,这也是一样的。

public ArrayDeque(int numElements)看起来 numElements 只将双端队列初始化为该大小,但不将其强制为最大长度。

最佳答案

可能不会。 LinkedHashMap 有一些工具可以使用逐出策略构建缓存,但这对于您想要的东西来说可能有点矫枉过正。只需扩展双端队列并添加您的自定义逻辑;-)


编辑:

class MyFixedSizeDeque<T> extends ArrayDeque<T>
{
private int maxSize;
public MyDeque(int size)
{
this.maxSize = size;
}

@Override
public void addLast(T e)
{
this.addLast(e);
if(this.size() > maxSize)
this.removeFirst();
}
}

我的 Java 有点生疏,您可能想要重载更多的方法(或切换到组合而不是继承),但我希望您能理解...

关于java - 是否有任何实现 maxlen 的 java Deque,如 python collections.deque?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30260448/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com