What is the LinkedList.offer method in Java?

The offer method can be used to add the specified element as the last element of the LinkedList.

A linked list is a collection of linear data elements. Each element or node has two parts:

  • data part
  • reference part

The data part has the value and the reference part has the address link to the next element. The elements are not indexed, so random access is not possible like it would be in arrays. Instead, we traverse from the beginning of the list and access the elements.

In Java, the LinkedList is the doubly-linkedEach node contains three fields: two link fields (one for the previous element and another for the next element) and one data field. list implementation of the List and Dequeue interfaces. The LinkedList class presents in the java.util package.

Syntax

public boolean offer(E e);

Argument

This method takes the element to be added to the list as an argument.

Return value

This method returns true if the element is added. Otherwise, false is returned.

Code

The code below demonstrates how to use the offer method.

import java.util.LinkedList;
class LinkedListOfferExample {
public static void main( String args[] ) {
LinkedList<String> list = new LinkedList<>();
list.offer("hello");
System.out.println("The list is " + list);
list.offer("hi");
System.out.println("The list is " + list);
}
}

Explanation

In the code above:

  • In line 1, we imported the LinkedList class.
import java.util.LinkedList;
  • In line 4, we created a LinkedList object with the name list.
LinkedList<String> list = new LinkedList<>();
  • In line 5, we used the offer method of the list object to add an element, "hello", as the tail element of the list. Then we printed the list.
list.offer("hello");
list; // ["hello"]
  • In line 7, we used the offer method of the list object to add an element, "hi", as the tail element of the list. Then we printed the list.
list.offer("hi");
list; // ["hello", "hi"]

Free Resources