Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java LinkedList offer() method
Syntax and Examples


Introduction to offer() in Java LinkedList

The offer() method is a part of the Deque interface and implemented by classes like LinkedList. It attempts to insert the specified element at the tail end of a deque (double-ended queue). Unlike its cousin, add(), which throws an exception if the operation can't be completed, offer() returns false in such cases. This makes it safer when dealing with potentially full or restricted deques.

Syntax

public boolean offer(E e)

Parameters

Parameter Description
e The element to be inserted at the tail of the deque.

Return Value

Returns true if the element was successfully added, and false if it couldn't (e.g., if the deque is full and is not unbounded).

Examples

Example 1: Basic Insertion

This example shows how to add an element to a LinkedList using `offer()`. Since LinkedLists are unbounded, the insertion should always succeed.

import java.util.LinkedList;

public class OfferExample {
    public static void main(String[] args) {
        LinkedList myList = new LinkedList<>();
        boolean success = myList.offer("Apple");

        System.out.println("Insertion successful: " + success);
        System.out.println("List contents: " + myList);
    }
}
Insertion successful: true
List contents: [Apple]

In this example, the string "Apple" is added to the LinkedList myList. The `offer()` method returns true because the insertion was successful.

Example 2: Using a Bounded Deque (ArrayDeque)

This demonstrates what happens when using an ArrayDeque, which is a bounded deque with a fixed capacity. If you try to add an element beyond its capacity, `offer()` will return false.

import java.util.ArrayDeque;

public class BoundedOfferExample {
    public static void main(String[] args) {
        ArrayDeque myBoundedDeque = new ArrayDeque<>(2); // Capacity of 2

        System.out.println("Adding first element: " + myBoundedDeque.offer(1));
        System.out.println("Adding second element: " + myBoundedDeque.offer(2));
        System.out.println("Attempting to add third element: " + myBoundedDeque.offer(3));
        System.out.println("Deque contents: " + myBoundedDeque);
    }
}
Adding first element: true
Adding second element: true
Attempting to add third element: false
Deque contents: [1, 2]

Here, we create an ArrayDeque with a capacity of 2. The first two calls to `offer()` succeed. The third call fails and returns false because the deque is full.

Example 3: Handling Potential Failure

This example illustrates how you can handle the case where `offer()` might return false, especially when working with bounded deques. It demonstrates a retry mechanism.

import java.util.ArrayDeque;

public class OfferRetryExample {
    public static void main(String[] args) {
        ArrayDeque myBoundedDeque = new ArrayDeque<>(1);
        String itemToAdd = "Banana";

        if (myBoundedDeque.offer(itemToAdd)) {
            System.out.println("Successfully added: " + itemToAdd);
        } else {
            System.out.println("Failed to add: " + itemToAdd + ".  Try again later.");
        }
    }
}
Failed to add: Banana . Try again later.

This code attempts to add the string "Banana" to an ArrayDeque with a capacity of 1. If the deque is full, the `else` block will execute, indicating that the insertion failed and suggesting a retry.

Example 4: Checking size before offer

This example shows how you can use the `size()` method to check if a bounded Deque has space available before attempting an `offer()`. This avoids directly checking for failure from `offer` itself.

import java.util.ArrayDeque;

public class OfferWithSizeCheckExample {
    public static void main(String[] args) {
        ArrayDeque myBoundedDeque = new ArrayDeque<>(2);
        int itemToAdd = 5;

        if (myBoundedDeque.size() < myBoundedDeque.capacity()){
            boolean success = myBoundedDeque.offer(itemToAdd);
            System.out.println("Adding element: " + itemToAdd + ", Success: " + success);
        } else {
           System.out.println("Deque is full, cannot add element.");
        }
    }
}
Adding element: 5, Success: true

The example checks the size of `myBoundedDeque` against its capacity. If the size is less than the capacity then it adds the element and prints a success message.


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M