In this method you can find and delete the element at the head of the deque. The poll( ) method gives back the element at the head of the deque and delete them from the underlying deque, or returns 'null' if the underlying deque is empty.
poll( ) method of Deque Interface in Java.
In this section we will discuss how can poll( ) method be implemented in Deque interface in java
Syntax
E poll()
This method removes the element at the head of the deque.
In this method you can find and delete the element at the head of the deque. The poll( ) method gives back the element at the head of the deque and delete them from the underlying deque, or gives back 'null' if the underlying deque is vacate. The remove() method is different from this method only by their behavior, as the remove() method throws 'NoSuchElementException' if the underlying deque is empty whereas the poll() method returns 'null'.
Parameter description
This method does not take any argument, but it retrieves and delete the head element of the underlying deque, or returns null if deque is empty.
Example of poll() method
In this example we will show you how does poll() method work in Deque interface. Through this example we will show how you can delete the element at the head of the underlying deque and count the total number of elements in deque.
Example :
package devmanuals.com; import java.util.Deque; import java.util.LinkedList; import java.util.Iterator; public class DequePoll { public static void main(String[] args) { Deque<String> dq = new LinkedList<String>(); dq.add("Java"); dq.add("Dev"); dq.add("Manuals"); dq.add(".Com"); System.out.println("Is deque empty : " + dq.isEmpty()); System.out.println("Elements of deque : " + dq); System.out.println("Size of deque before removing an element : "+dq.size()); System.out.println("Now after removing the head of the deque new deque is "); Object obj = dq.poll(); System.out.println(dq); System.out.println("Removed element is = " + obj); System.out.println("Size of deque after removing element : "+dq.size()); System.out.println("Removes all the elements from deque"); Iterator iq = dq.iterator(); while (iq.hasNext()) { dq.poll(); } System.out.println(dq); System.out.println("Is deque empty : " + dq.isEmpty()); // Here implementation of the poll( ) method will display 'null' System.out.println(dq.poll()); } }
Output :
Is deque empty : false Elements of deque : [Java, Dev, Manuals, .Com] Size of deque before removing an element : 4 Now after removing the head of the deque new deque is [Dev, Manuals, .Com] Removed element is = Java Size of deque after removing element : 3 Removes all the elements from deque [] Is deque empty : true null |
[ 0 ] Comments