In this guide, you will learn about the Java Queue poll() example method in Java programming and how to use it with an example.
1. Java Queue poll() example Method Overview
Definition:
The poll() method of the Java Queue interface retrieves and removes the head of the queue, or returns null if the queue is empty.
Syntax:
E element = queue.poll();
Parameters:
None
Key Points:
- The method returns the head of the queue or null if the queue is empty.
- Unlike the remove() method in the Queue interface, the poll() method does not throw an exception when the queue is empty but rather returns null.
- This method is often used in situations where you want to safely retrieve an element from the queue without risking an exception if the queue is empty.
- The element returned by poll() is no longer available in the queue.
2. Java Queue poll() example Method Example
import java.util.LinkedList;
import java.util.Queue;
public class QueuePollExample {
public static void main(String[] args) {
Queue<String> fruits = new LinkedList<>();
// Add elements to the queue
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Poll the queue
String firstFruit = fruits.poll();
System.out.println("Polled fruit: " + firstFruit);
System.out.println("Queue after polling: " + fruits);
// Poll an empty queue
fruits.clear(); // Clearing the queue
String resultWhenEmpty = fruits.poll();
System.out.println("Result of polling an empty queue: " + resultWhenEmpty);
}
}
Output:
Polled fruit: Apple Queue after polling: [Banana, Cherry] Result of polling an empty queue: null
Explanation:
In the provided example:
1. We instantiated a LinkedList, which is an implementation of the Queue interface.
2. We added elements to the queue using the add() method.
3. We then used the poll() method to retrieve and remove the head of the queue, displaying the result and the state of the queue afterward.
4. For demonstration purposes, we cleared the queue using the clear() method and tried polling again, which, as expected, returned null since the queue was empty.
Using poll(), developers can safely and gracefully handle scenarios where the queue might be empty, without worrying about unchecked exceptions that methods like remove() might throw.
Related Stack and Queue Class methods
Java Queue offer() exampleJava Queue poll() example
Java Queue peek() example
Java Stack push() example
Java Stack pop() example
Java Stack peek() example
Java Stack search() example
Comments
Post a Comment
Leave Comment