How implementation of java.util.queue uses LIFO?

Viewed 21207

In Java doc:

[...] Among the exceptions are priority queues, which order elements according to a supplied comparator, or the elements' natural ordering, and LIFO queues (or stacks) which order the elements LIFO (last-in-first-out)

How implementation of java.util.queue uses LIFO instead of FIFO?

7 Answers

Implementation of the Queue can base on FIFO, priorities and LIFO - that is what official documentation says.

When a programmer first sees "Queue" he automatically thinks "it must be FIFO order" (or eventually prioritized order). But as documentation says there must be possibility to use Queue interface for LIFO ordering. Let me explain you how it can be done.

// FIFO queue usage
Queue<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);

queue.remove(); // returns 1
queue.remove(); // returns 2

// LIFO queue usage
Queue<Integer> queue = Collections.asLifoQueue(new ArrayDeque<>());
queue.add(1);
queue.add(2);

queue.remove(); // returns 2
queue.remove(); // returns 1

As you can see depending on the implementation, Queue interface can be used also as a LIFO.

I made a LIFO queue with limited size. Limited size is maintained by replacing the oldest entries with the new ones. The implementation is based on LinkedList.

package XXXX;

import java.util.LinkedList;

public class LIFOQueueLimitedSize<E> extends LinkedList<E> {


/**
 * generated serial number
 */
private static final long serialVersionUID = -7772085623838075506L;

// Size of the queue
private int size;

// Constructor
public LIFOQueueLimitedSize(int crunchifySize) {

    // Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy
    this.size = crunchifySize;
}

// If queue is full, it will remove oldest/first element from queue like FIFO
@Override
synchronized public boolean add(E e) {

    // Check if queue full already?
    if (super.size() == this.size) {
        // remove element from queue if queue is full
        this.remove();
    }
    return super.add(e);
}
}
Related