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
LinkedListis thelist implementation of the doubly-linked Each node contains three fields: two link fields (one for the previous element and another for the next element) and one data field. ListandDequeueinterfaces. TheLinkedListclass presents in thejava.utilpackage.
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
LinkedListclass.
import java.util.LinkedList;
- In line 4, we created a
LinkedListobject with the namelist.
LinkedList<String> list = new LinkedList<>();
- In line 5, we used the
offermethod of thelistobject 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
offermethod of thelistobject to add an element,"hi", as the tail element of the list. Then we printed the list.
list.offer("hi");
list; // ["hello", "hi"]