addFirst(e) method of BlockingDeque Interface in Java.

addFirst(e) method of BlockingDeque Interface in Java.


Posted in : Core Java Posted on : February 23, 2011 at 3:49 PM Comments : [ 0 ]

In this method an element is to be inserted into the underlying deque if currently space is available i.e. an insertion operation is performed without breaking the

addFirst(e) method of BlockingDeque Interface in Java.

In this section we will discuss how can addFirst(e) method be implemented in BlockingDeque interface in java.

Syntax

void addFirst(E e) 

This method adds a specific element at the first position into the deque.

In this method an element is to be inserted into the underlying deque if currently space is available i.e. an insertion operation is performed 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. More formally the offerFirst() method is preferred when capacity-limited deque is used.

Parameter description

e : It takes an element what do you want to add into the deque.

Example of addFirst(E e) method

In this example we will show you how does addFirst(e) method work in BlockingDeque interface. This example will help you to understand how can you insert a specified element at the first position into the deque. Further we will see after using addFirst() method what the effect this method put on the previous deque (e.g. size).

Example :

package devmanuals.com;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
class AddFirst implements Runnable 
{
  BlockingDeque<Integer> bdq;
  public AddFirst(BlockingDeque<Integer> bdq
  {
    this.bdq = bdq;
  }
  public void run() 
  {
    System.out.println("Elements of deque are : ");
    int i;
   for(i=0; i<5;i++)
      bdq.add(i);
      System.out.println(bdq);
      System.out.println("Size of deque = "+bdq.size());
    try {

       Thread.sleep(1000);
        bdq.addFirst(5);
      }
      catch (InterruptedException e
      {
        e.printStackTrace();
      }
      System.out.println("Deque after adding element : "+bdq);
      System.out.println("Size of deque after adding element = "+bdq.size());
  }
}
public class BdqAddFirst {
  public static void main(String[] args) {
    BlockingDeque<Integer> bdq = new LinkedBlockingDeque<Integer>();
   Runnable a = new AddFirst(bdq);
    new Thread(a).start();
  }
}

Output :

Elements of deque are :

[0, 1, 2, 3, 4]

Size of deque = 5

Deque after adding element : [5, 0, 1, 2, 3, 4]

Size of deque after adding element = 6 

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics