Skip to main content

How do I push and pop items from a list on a LIFO basis

In this Q&A, we'll go over the options available in Java to push and pop items from a list on a Last In First Out ( LIFO ) basis.

Collections framework has a List interface but not a Stack interface.  But, Collections.asLifoQueue() method provides the ability to convert a queue into a LIFO queue.  One other option is to use the Java 1 Stack class .

Lets go over the two options below.

LIFO Queue

Note that the FIFO->LIFO queue conversion happens before adding elements to the queue.

Correct usage of  LIFO queue:
public static void lifoQueue() {
    LinkedList<Integer> li = new LinkedList<>();
    // convert before adding elements to the queue
    Queue<Integer> q = Collections.asLifoQueue(li);
    for( int i=0; i<1000; ++i) {
        q.add(i);
    }
    int i = q.poll();
    assert(i == 999 );
}

Incorrect usage of  LIFO queue:
public static void incorrectLifoQueue() {
    LinkedList<Integer> li = new LinkedList<>();
    for( int i=0; i<1000; ++i) {
        li.add(i);
    }
    // queue conversion happens after adding elements to the queue
    Queue<Integer> q = Collections.asLifoQueue(li);
    int i = q.poll();
    assert(i == 0);  // not the desired result
}

Stack

public static void stack() {
    Stack<Integer> si = new Stack<>();
    for( int i=0; i<1000; ++i) {
        si.push(i)
    }
    int i = si.pop();
    assert(i == 999);
}

Comments