What is the LinkedList.poll method in Java?
What is LinkedList?
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 Array is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedListis theimplementation of the List and Deque interfaces. The Doubly-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. LinkedListclass present in thejava.utilpackage.
What is the poll method of the LinkedList class?
The poll method can be used to get and remove the first element (head element) of the LinkedList.
Syntax
public E poll();
This method doesn’t take any arguments.
This method retrieves and removes the first element of the list. If the list is empty then null is returned.
Code
The code below demonstrates how to use the poll method.
import java.util.LinkedList;class LinkedListPoll {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.poll() returns : " + list.poll());System.out.println("The list is " + list);}}
Explanation
In the code above:
-
In line 1, we imported the
LinkedListclass. -
In line 4, we created a
LinkedListobject with the namelist. -
From lines 5 to 7, we used the
addmethod of thelistobject to add three elements ("1","2","3") to the list. -
In line 10, we used the
pollmethod of thelistobject to get and remove the first element.