add(E e) method of Queue Interface in Java.

add(E e) method of Queue Interface in Java.


Posted in : Core Java Posted on : January 31, 2011 at 5:31 PM Comments : [ 0 ]

In this section we will discuss how can add(E e) method be implemented in Queue interface in java.

add(E e) method of Queue Interface in Java.

In this section we will discuss how can add(E e) method be implemented in Queue interface in java.

Syntax 

boolean add (E e)

This method inserts an element into a queue and returns 'true' if operation of adding becomes successful, otherwise displays 'IllegalStateException' exception.

In Queue interface this method is inherited from the collection. Through this method you can insert a specified element unless it would not infract the capacity restrictions of queue. In such case if queue is full, the add operation gets fail and this method throws an 'IllegalStateException' exception otherwise, returns true. In particular, Queue does not allow to insert null elements whereas some implementations, such as 'LinkedList', allow insertion of null.

Parameter description

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

Example of add(E e) method

In this example we will show you, how does an add(E e) method work in Queue interface. This Example will help you to understand  how an element can be added into the queue. Through this example we will show you how you can add a specified element into Queue, and count the total number of elements of queue before and after adding the elements.

 Example :

package devmanuals.com;
import java.util.Queue;
import java.util.LinkedList;
public class QueueAddElement {
  public static void main(String[] args) {
    Queue<Integer> q = new LinkedList<Integer>();
    System.out.println("Initially the size of queue is " + q.size());
    System.out.println("Elements in queue : "+q);
    q.add(1);
    q.add(2);
    System.out.println("After addition of elements into queue, the elements are :"+q);
    System.out.println("And the size of queue : " + q.size());
    System.out.println("Now insert a new element '4'");
    q.add(4);
    System.out.println("Then the new Elements of queue are : " + q);
    System.out.println("And the size of new queue = " + q.size());
  }
}

Output :

Initially the size of queue is 0

Elements in queue : []

After addition of elements into queue, the elements are :[1, 2]

And the size of queue : 2

Now insert a new element '4'

Then the new Elements of queue are : [1, 2, 4]

And the size of new queue = 3 

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics