删除“第一”来自Set的对象 [英] Removing the "first" object from a Set
问题描述
在某些情况下,我需要逐出Java Set
中的最旧元素。该集使用 LinkedHashSet实现
,这很简单:只需删除set迭代器返回的第一个元素:
Under certain situations, I need to evict the oldest element in a Java Set
. The set is implemented using a LinkedHashSet
, which makes this simple: just get rid of the first element returned by the set's iterator:
Set<Foo> mySet = new LinkedHashSet<Foo>();
// do stuff...
if (mySet.size() >= MAX_SET_SIZE)
{
Iterator<Foo> iter = mySet.iterator();
iter.next();
iter.remove();
}
这很难看:3行可以做我可以如果我使用 SortedSet
,则使用1行(由于其他原因,此处不能选择 SortedSet
):
This is ugly: 3 lines to do something I could do with 1 line if I was using a SortedSet
(for other reasons, a SortedSet
is not an option here):
if (/*stuff*/)
{
mySet.remove(mySet.first());
}
所以有更简洁的方法,没有:
So is there a cleaner way of doing this, without:
- 更改
设置
实施,或 - 编写静态实用程序方法?
- changing the
Set
implementation, or - writing a static utility method?
任何利用番石榴没问题。
< sub>我完全知道集合没有固有的顺序。我要求删除迭代顺序定义的第一个条目。
推荐答案
LinkedHashSet是LinkedHashMap的包装器它支持简单的删除最旧策略。要将它用作Set,你可以做
LinkedHashSet is a wrapper for LinkedHashMap which supports a simple "remove oldest" policy. To use it as a Set you can do
Set<String> set = Collections.newSetFromMap(new LinkedHashMap<String, Boolean>(){
protected boolean removeEldestEntry(Map.Entry<String, Boolean> eldest) {
return size() > MAX_ENTRIES;
}
});
这篇关于删除“第一”来自Set的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!