E removeLast() This method removes the element at the tail of the deque.
removeLast() method of Deque Interface in Java.
In this section we will discuss how can removeLast() method be implemented in Deque Interface in java.
Syntax
E removeLast()
This method removes the element at the tail of the deque.
In this method, the last element of deque is deleted. This method is equivalent to the pollLast() method as this method finds and deletes the element at the tail position of the deque, the removeLast() method also works similar to the pollLast() method. This method is slightly different from the pollLast() method in terms the removeLast() method and displays 'NoSuchElementException' whereas pollLast() method returns 'null' if the underlying deque is empty.
Parameter description
This method does not take any argument, but it retrieves and deletes the last element of the underlying deque, or throws exception if deque is empty.
Example of removeLast() method
In this example, we will show you how does removeLast() method work in Deque interface. Through this example we will show how you can delete the element at the bottom 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 DequeRemoveLast { 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"); dq.add(10); 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 last element from deque new deque is "); Object obj = dq.removeLast(); System.out.println(dq); System.out.println("Removed element is = " + obj); System.out.println("Size of deque after removing element : "+ dq.size()); // Removes all the elements from deque Iterator it = dq.iterator(); while (it.hasNext()) { dq.remove(); } System.out.println("After removing all the elements "); System.out.println("from deque then deque = " + dq); System.out.println("Is deque empty : " + dq.isEmpty()); // Here implementation of the removeLast( ) method will display an // exception System.out.println(dq.removeLast()); } }
Output :
Is deque empty : false Elements of deque : [11, Java, Dev, Manuals, .Com, 10] Size of deque before removing an element : 6 Now after removing the last element from deque new deque is [11, Java, Dev, Manuals, .Com] Removed element is = 10 Size of deque after removing element : 5 After removing all the elements from deque then deque = [] Is deque empty : true Exception in thread "main" java.util.NoSuchElementExceptionat java.util.LinkedList.remove(Unknown Source) at java.util.LinkedList.removeLast(Unknown Source) at devmanuals.com.DequeRemoveLast.main( DequeRemoveLast.java:38) |
[ 0 ] Comments