Java LinkedList poll() Method
Example
Take the first item out of a list:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
System.out.println(cars.poll());
System.out.println(cars);
}
}
Definition and Usage
The poll() method removes the first item from the list and returns it.
If the list is empty, it returns null. The removeFirst() method does the same, but it throws an exception when the list is empty.
Tip: Use the offer() method to add an item to the end of the list. Together, offer() and poll() let you use the list as a queue (a list where items are added at the end and taken from the front).
Syntax
public T poll()
T refers to the data type of items in the list.
Parameter Values
None.
Technical Details
| Returns: | The first item in the list (the item that was removed), or null if the list is empty. |
|---|
Related Pages
❮ LinkedList Methods