Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Queue

A queue: elements are added at the tail and taken from the head.

Available since: Java 1.5

Syntax

public interface Queue<E> extends Collection<E>

Examples

A first-in, first-out queue:

void main() {
    Queue<String> line = new ArrayDeque<>();
    line.offer("Anna");
    line.offer("Oleg");
    line.offer("Ivan");
    while (!line.isEmpty()) {
        IO.println("Serving " + line.poll());
    }
}

Output:

Serving Anna
Serving Oleg
Serving Ivan

Notes

The main methods come in pairs: offer()/add() add, poll()/remove() take, peek()/element() look at the head. The first method of each pair returns false or null on failure, the second throws an exception. The usual implementation is ArrayDeque; a priority queue is PriorityQueue.

See also

  • Queue.offer() — Adds an element to the tail of a queue.
  • Queue.poll() — Takes and removes the head of a queue.
  • Queue.peek() — Returns the head of a queue without removing it.
  • ArrayDeque — A fast array-based double-ended queue — a replacement for `Stack` and `LinkedList`.
  • PriorityQueue — A queue that always hands out the smallest (or highest-priority) element.

In the tutorial

  • Queues and deques — Queues in Java: Queue and ArrayDeque, a stack built on Deque, the offer, poll and peek methods and the PriorityQueue.

Thanks for reading!

Donate to the site — we work hard for you.