Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Queue.offer() — Try to insert an element into a queue

`offer(E e)` tries to insert an element without waiting for space. It returns `true` if the element was added and `false` if no space is available.

Version: Java SE 21

Syntax

boolean offer(E e);  // declared in java.util.Queue<E>

Queue.offer() is shorthand for the method name, not a no-argument call. The java.util.Queue<E> interface declares boolean offer(E e): E is the queue's element type, and e is the element you pass in queue.offer(e).

The method does not wait for space. It returns true if it inserts the element and false if there is no room. Under the same capacity constraint, add(E e) throws IllegalStateException. Check the result of offer when a full queue is an expected case. false does not replace exceptions: depending on the queue's restrictions, the method may throw NullPointerException for a disallowed null, ClassCastException for an incompatible element type, or IllegalArgumentException for a disallowed property of the element.

In a FIFO queue, insertion is at the tail; other implementations may order elements differently. poll() removes and returns the head element, or returns null if the queue is empty. The overload offer(E e, long timeout, TimeUnit unit) belongs to BlockingQueue and can wait for space up to the specified timeout. The one-argument method on Queue does not wait for space.

Examples

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

public class QueueOfferExample {
    public static void main(String[] args) {
        Queue<String> queue = new ArrayBlockingQueue<>(2);

        System.out.println(queue.offer("A"));
        System.out.println(queue.offer("B"));
        System.out.println(queue.offer("C"));
        System.out.println(queue.poll());
        System.out.println(queue.poll());
    }
}

Result

true
true
false
A
B

`ArrayBlockingQueue` has a fixed capacity of 2 and uses FIFO order. `A` and `B` are inserted; offering `C` returns `false`. The two `poll()` calls remove `A` and then `B`.

Related lessons

  • Java · Lesson 61 · Basic · Version: 2

Sources