Java collection is used for special scrolling and looping queues
I'm looking for something similar to concurrentlinkedqueue, but I have the following behavior:
>When I view the () / poll () queue, it retrieves the head without deleting it, and then advances a node of the head to tail > when head = = tail, the next time I view () / poll (), the head will be reset to its original node (so it is a "loop" behavior)
So, if I create a queue like this:
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 way, I can peek / poll all day and the queue will roll my queue over and over again
Does JRE come with such a thing? If not, could it be something in Apache commons collections or other third-party libraries? Thank you in advance!
Solution
You can do this by using an ArrayList with a pointer to head (I won't write out the entire class, but this is 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 don't really specify how the addition should work, but you should be able to use the default addition of ArrayList
