Question

I'm looking for something similar to ConcurrentLinkedQueue, but with the following behaviors:

  • When I peek()/poll() the queue, it retrieves the HEAD, does not remove it, and then subsequently advances the HEAD one node towards the TAIL
  • When the HEAD == TAIL, the next time I peek()/poll(), the HEAD is reset to its original node (thus "circular" behaviour)

So if I created the queue like so:

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

In this fashion, I can peek/poll all day long, and the queue will just keep scrolling through my queue, over and over again.

Does the JRE ship with anything like this? If not, perhaps something in Apache Commons Collections, or some other 3rd party lib? Thanks in advance!

Was it helpful?

Solution

You could implement by using an ArrayList with a pointer to the HEAD (I'm not going to write out the whole class, but here's the peek method):

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

You didn't really specify how add was supposed to work exactly, but you should be able to use the default add from ArrayList.

OTHER TIPS

I don't think it exists in the JRE.

How about Google Guava's Iterables.cycle?

Something like this:

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

will output

A B C D A B C D A B C D ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top