Skip to main content

How do I add and retrieve elements from a list on a FIFO basis

In this Q&A, we'll go over how to add and retrieve elements from a Queue on a First In First Out  (FIFO) basis.

Java collections framework provides the Queue interface and multiple concrete implementations.  In this Q&A we'll go over how to achieve it using LinkedList.

LinkedList is alsoQueue.  You can add or poll for elements using it.

In the example below, please note the difference between the poll() and remove() methods.

import java.util.LinkedList;
import java.util.NoSuchElementException;

public class QueueTest {
    public static void fifoQueue() {
        LinkedList<Integer> li = new LinkedList<>();
        for(int i = 0; i < 1000; ++i )
            li.add(i);
        for(int i = 0; i < 1000; ++i ) {
            Integer i1 = li.poll();
            assert ( i1 == i);
        }

        // returns null if there are no elements
        Integer i2 = li.poll();
        assert(  i2 == null );
        int s = li.size();
        assert( s == 0 );

        try {
            // throws an exception if there are no elements
            Integer r = li.remove();
        } catch( Exception e ) {
            assert( e instanceof NoSuchElementException);
            System.out.println("NoSuchElementException assertion passed");
        }
        System.out.println("all assertions passed");

    }
    public static void main( String[] args ) {
        fifoQueue();
    }
}

Comments