javacollectionsqueuecircular-bufferapache-commons-collection

Java Collection for special scrolling, circular queue


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

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 third party lib?


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.