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

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


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

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

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

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

Syntax

boolean offer(E e)

This method adds an element into a queue and returns 'true' if element is added to a queue or returns false.

In this method you can insert a specified element in queue. This method is preferably used when we are restricted with the capacity of queue. It inserts an element to the underlying queue if it is possible to do so instantly without breaking the capacity limitation of the queue. The add(E e) method is different from this method only by their behavior, the offer(E e) method returns 'false' if insertion of an element in queue gets fail whereas add(E e) method throws an 'IllegalStateException' exception.

Parameter description

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

Example of offer(E e) method 

In this example we will show you how does an offer (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 how can you add a specified element into Queue, and count the total number of elements of queue before and after adding the elements and the returned value of this method depending upon the operation.

 Example :

package devmanuals.com;
import java.util.Queue;
import java.util.LinkedList;
public class QueueOfferElement {
  public static void main(String[] args) {
    Queue<String> q = new LinkedList<String>();
    System.out.println("Initially the size of queue is " + q.size());
    System.out.println("Elements in queue : " + q);
    q.offer("Ram");
    q.offer("Shyam");
    q.offer("Radhey Shayam");
    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 'JaiRam'");
    boolean b = q.offer("Jai Ram");
    System.out.println("Then the new Elements of queue are : " + q);
    System.out.println("Inserts the specified element : " + b);
    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 :  
[Ram, Shyam, Radhey Shayam]

And the size of queue : 3

Now insert a new element 'JaiRam'

Then the new Elements of queue are : 
[Ram, Shyam, Radhey Shayam, Jai Ram]

Inserts the specified element : true

And the size of new queue = 4 

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics