IAmYourFaja
IAmYourFaja

Reputation: 56912

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?

Upvotes: 4

Views: 2403

Answers (2)

wjans
wjans

Reputation: 10115

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 ...

Upvotes: 6

quazzieclodo
quazzieclodo

Reputation: 831

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.

Upvotes: 2

Related Questions