What is the LinkedList.pollFirst() method in Java?
What is 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 in Array objects is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedListclass is aimplementation of the doubly-linked list Kind of linked list. Each node contains three fields: two link fields (one for the previous element and another for the next element) and one data field. ListandDequeinterfaces. TheLinkedListclass is present in thejava.utilpackage.
What is the pollFirst() method of the LinkedList class?
The pollFirst() method can be used to get and remove the first element of a LinkedList object.
Syntax
The syntax of the pollFirst() method is as follows.
public E pollFirst();
This method doesn’t take any arguments.
This method retrieves and removes the first element of the specified LinkedList. If the list is empty. then null is returned.
Code
The code below demonstrates how to use the pollFirst() method.
import java.util.LinkedList;class LinkedListPollFirst {public static void main( String args[] ) {LinkedList<String> list = new LinkedList<>();list.add("1");list.add("2");list.add("3");System.out.println("The list is " + list);System.out.println("list.pollFirst() returns : " + list.pollFirst());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<>();
- From lines 5 to 7, we used the
add()method of thelistobject to add three elements ("1","2","3") to the list.
list.add("1");
list.add("2");
list.add("3");
- In line 10, we used the
pollFirst()method of thelistobject to get and remove the first element.
list.pollFirst(); // "1"
list; // ["2", "3"]