What is the LinkedList.offerLast method in Java?
What is offerLast method of the LinkedList class?
The offerLast method is used to add the specified element as the last element of a LinkedList.
LinkedList
A Linked List is a collection of linear data elements. Each element/node contains data and reference parts. 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 like an Array is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedListis the doubly-linked list implementation of the List and Deque interfaces.
The LinkedList class present in the java.util package.
Syntax
public boolean offerLast(E e);
Parameters
The offerLast method takes the element to be added to the list as a parameter.
Return value
The offerLast method returns true if the element is added. Otherwise, false is returned.
Code
The code below demonstrates how to use the offerLast method.
import java.util.LinkedList;class LinkedListOfferLastExample {public static void main( String args[] ) {LinkedList<String> list = new LinkedList<>();list.offerLast("hello");System.out.println("The list is " + list);list.offerLast("hi");System.out.println("The list is " + list);}}
Explanation
- In line number 1: We import the
LinkedListclass.
import java.util.LinkedList;
- In line number 4: We create a
LinkedListobjects with the namelist.
LinkedList<String> list = new LinkedList<>();
- In line number 5: We use the
offerLastmethod of thelistobject to add an element ("hello") as the last element of the list. Then we print the list.
list.offerLast("hello");
list; // ["hello"]
- In line number 7: We use the
offerLastmethod of thelistobject to add an element ("hi") as the last element of the list. Then we print the list.
list.offerLast("hi");
list; // ["hello", "hi"]