E pollFirst() This method deletes the element at the head of the deque.
pollFirst() method of Deque Interface in Java.
In this section we will discuss how can pollFirst() method be implemented in Deque interface in java.
Syntax
E pollFirst()
This method deletes the element at the head of the deque.
This method is similar to the poll() method as this method finds and deletes the element at the head position of the deque, the pollFirst() method also works exactly like the poll() method does. This method finds the first element and deletes them from the underlying deque. It returns the element which is just removed from the first position, or returns 'null' if the underlying deque is vacate.
Parameter description
This method does not take any argument, but it retrieves and deletes the first element of the underlying deque, or returns null if deque is empty.
Example of pollFirst() method
In this example we will show you how does pollFirst() method work in Deque interface. Through this example we will show how you can delete the element at the top position 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 DequePollFirst { public static void main(String[] args) { Deque dq = new LinkedList(); dq.add(11); 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.pollFirst(); 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 lq = dq.iterator(); while (lq.hasNext()) { dq.poll(); } System.out.println(dq); System.out.println("Is deque empty : " + dq.isEmpty()); // Here implementation of the pollFirst( ) method will display 'null' System.out.println(dq.pollFirst()); } }
Output :
Is deque empty : false Elements of deque : [11, Java, Dev, Manuals, .Com] Size of deque before removing an element : 5 Now after removing the head of the deque new deque is [Java, Dev, Manuals, .Com] Removed element is = 11 Size of deque after removing element : 4 Removes all the elements from deque [] Is deque empty : true null |
[ 0 ] Comments