Java Collection用于特殊滚动,循环队列

IAm*_*aja 3 java queue collections circular-buffer apache-commons-collection

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

  • 当我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
Run Code Online (Sandbox Code Playgroud)

以这种方式,我可以整天偷看/轮询,队列将一遍又一遍地滚动我的队列.

JRE是否附带这样的东西?如果没有,可能是Apache Commons Collections或其他第三方库中的某些东西?提前致谢!

wja*_*ans 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);
}
Run Code Online (Sandbox Code Playgroud)

将输出

A B C D A B C D A B C D ...
Run Code Online (Sandbox Code Playgroud)