addFirst(E e) method of Deque Interface in Java.

addFirst(E e) method of Deque Interface in Java.


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

In the following example we will show how can addFirst(E e) method be implemented in Deque interface in java.

addFirst(E e) method of Deque Interface in Java.

In the following example we will show how can addFirst(E e) method be implemented in Deque interface in java.

Syntax

void addFirst(E e) 

This method adds the element at the front of the deque.

In this method you can insert a specified element at the front of the underlying deque. It inserts an element to the underlying deque if it is possible to do so instantly without breaking the capacity limitation of deque. This method returns no value but, it throws an 'IllegalStateException' exception when the operation of adding an element into deque gets failure.

Parameter description

e : It is the element to be added.

Example of addFirst(E e) method

This example will help you to understand how a specified element can be added at the front of the deque and how it works. In the following example at first we will  insert elements into the deque by an add(e) method then after check the total number of elements into deque before and after inserting the element in the whole program and finally we will implement the addFirst(E e) method that adds the element at the front of the deque. We will also show what the effect of this method  may put on deque such as size of deque and how previously front element is shifted to the second element.

Example :

package devmanuals.com;
import java.util.Deque;
import java.util.LinkedList;
public class DequeAddFirst {
  public static void main(String args[]) {
    Deque dq = new LinkedList();
    dq.add(11);
    dq.add(12);
    System.out.println("Elements of previous deque are :" + dq);
    System.out.println("And the size of dqueue : " + dq.size());
    System.out.println("Now insert a new element '10' at the front of the deque");
    // This method will add the element at the front of the deque.
    dq.addFirst(10);
    System.out.println("Then the new Elements of dqueue are : " + dq);
    System.out.println("And the size of new dqueue = " + dq.size());
  }
}

Output :

Elements of previous deque are :[11, 12]

And the size of dqueue : 2

Now insert a new element '10' at the front of the deque

Then the new Elements of dqueue are : [10, 11, 12]

And the size of new dqueue = 3

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics