remove() method of Deque Interface in Java.

remove() method of Deque Interface in Java.


Posted in : Core Java Posted on : February 5, 2011 at 6:03 PM Comments : [ 0 ]

E remove() This method removes the element from the deque.

remove() method of Deque Interface in Java.

In the following example we will show how can remove() method be implemented in Deque Interface in java.

Syntax

E remove()

This method removes the element from the deque.

In this method the head element of deque is removed. This method is slightly different from the poll() method in terms the remove() method displays 'NoSuchElementException' whereas poll() method returns 'null' if the underlying deque has no element. This method is equivalent to the removeFirst() method.

Parameter description

This method has no argument but, it returns the front element of the deque.

Example of remove( ) method 

In this example we will show you how does remove() method work in Deque interface. Through this example we will show how you can delete the head of the underlying deque, and count the total number of elements in deque before and after removing the elements.

 Example :

package devmanuals.com;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Iterator;
public class DequeRemove {
  public static void main(String[] args) {
    Deque dq = new LinkedList();    
    dq.add(1);
    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 element : "+dq.size());
    System.out.println("Now after removing the head of the deque new deque is ");
    Object obj=dq.remove();
    System.out.println(dq);
    System.out.println("Removed element = "+obj);
    System.out.println("Size of deque after removing element : "+dq.size());
  System.out.println("Removes all the elements from deque");
    Iterator it = dq.iterator();
  while(it.hasNext())
   dq.remove();
  System.out.println(dq);
  System.out.println("Is deque empty : "+dq.isEmpty());
  //Here implementation of the remove( ) method will throw an exception 
  dq.remove();
  }
}

Output :

Is deque empty : false

Elements of deque : [1, Dev, Manuals, .com]

Size of deque before removing element : 4

Now after removing the head of the deque new deque is

[Dev, Manuals, .com]

Removed element = 1

Size of deque after removing element : 3

Removes all the elements from deque

[]

Is deque empty : true

Exception in thread "main" java.util.NoSuchElementException

at java.util.LinkedList.remove(Unknown Source)

at java.util.LinkedList.removeFirst(Unknown Source)

at java.util.LinkedList.remove(Unknown Source)

at devmanuals.com.DequeRemove.main(DequeRemove.java:30)

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics