I have a Circular queue, but I don't know how to get a certain item from some position, the header would be: public E peeki(int index) and using a generic Iterator.
Asked
Active
Viewed 498 times
0
-
Welcome to StackOverflow. Please take the [tour], learn asking good questions stackoverflow.com/help/how-to-ask, make a [mcve]. – Yunnosch May 01 '17 at 23:06
2 Answers
0
By design of Queue, you cannot do that. You can only peek the header of a Queue.
If you want to access elements by index, use List instead of Queue.

Nilesh Rajani
- 538
- 6
- 16
0
As Nilesh pointed out, Queue is not intended to be used with indexes. Anyway, you may implement your own class with custom behaviour using Queue and iterator to find an element by index. If it is the case your looking for, please, consider the following example:
public class QueueExample<E> {
private Queue<E> queue = new LinkedList<>();
public void add(E item) {
queue.add(item);
}
public E peek(int index) {
E item = null;
Iterator<E> iterator = queue.iterator();
while (iterator.hasNext()) {
E temp = iterator.next();
if (index-- == 0) {
item = temp;
break;
}
}
return item;
}
public static void main(String[] args) {
QueueExample<String> queueExample = new QueueExample<>();
queueExample.add("One");
queueExample.add("Two");
queueExample.add("Three");
System.out.println(queueExample.peek(0));
System.out.println(queueExample.peek(2));
System.out.println(queueExample.peek(1));
System.out.println(queueExample.peek(4));
}
}
The output (as expected):
One
Three
Two
null
Hope this helps.

Vasiliy Vlasov
- 3,316
- 3
- 17
- 20
-
Yeah, this should do the trick. Only problem though is that worst case performance of this would be O(n) whereas using a more suitable data structure (such as a list) in the first place can give O(1) running time – Nilesh Rajani May 04 '17 at 16:37