4

我正在寻找类似于 的东西ConcurrentLinkedQueue,但具有以下行为:

  • 当 I peek()/poll()队列时,它检索 HEAD,不删除它,然后将 HEAD 前进一个节点向 TAIL
  • 当 HEAD == TAIL 时,下一次 I peek()/ poll(), HEAD 重置为其原始节点(因此是“循环”行为)

因此,如果我像这样创建队列:

MysteryQueue<String> queue = new MysteryQueue<String>();
queue.add("A"); // The "original" HEAD
queue.add("B");
queue.add("C");
queue.add("D"); // TAIL

String str1 = queue.peek(); // Should be "A"
String str2 = queue.peek(); // Should be "B"
String str3 = queue.peek(); // Should be "C"
String str4 = queue.peek(); // Should be "D"
String str5 = queue.peek(); // Should be "A" again

以这种方式,我可以整天偷看/轮询,队列将不断滚动浏览我的队列,一遍又一遍。

JRE 附带这样的东西吗?如果没有,也许 Apache Commons Collections 或其他第三方库中的某些东西?

4

2 回答 2

5

我认为它不存在于 JRE 中。

Google Guava 的Iterables.cycle怎么样?

像这样的东西:

// items can be any type of java.lang.Iterable<T>
List<String> items = Lists.newArrayList("A", "B", "C", "D");
for(String item : Iterables.cycle(items)) {
    System.out.print(item);
}

将输出

A B C D A B C D A B C D ...
于 2013-11-15T15:32:31.243 回答
2

您可以使用带有指向 HEAD 的指针的 ArrayList 来实现(我不会写出整个类,但这里是 peek 方法):

public T peek() {
    if (list.size() == 0)
        return null;
    T ret = list.get(head);
    head++;
    if (head == list.size()) {
        head = 0;
    }
    return ret;
}

您并没有真正指定 add 应该如何准确工作,但您应该能够使用 ArrayList 中的默认 add。

于 2013-11-15T15:32:53.970 回答