javaiteratorqueuecircular-queue

Getting an item from one position in a Circular Queue using an iterator


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.


Solution

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