element( ) method of Deque Interface in Java.

element( ) method of Deque Interface in Java.


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

In this method you can retrieve the element at the top of the deque. This method returns the element, but does not remove at the head of the underlying deque.

element( ) method of Deque Interface in Java.

In this section we will discuss how can element( ) method be implemented in Deque interface in java.

Syntax

E element( )

This method returns an element at the top position of the deque.

In this method you can retrieve the element at the top of the deque. This method returns the element, but does not remove at the head of the underlying deque. It displays 'NoSuchElementException' exception if deque is empty. 

Parameter description 

This method does not take any argument but, it returns the element at the head position of the deque.

Example of element( ) method 

In this example we will show you, how does element( ) method work in Deque interface. In the following example we will show how you can retrieve the element at the head position of the underlying Deque, and count the total number of elements in deque. We also show what the exception will display through this method.

Example :

package devmanuals.com;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Iterator;
public class DequeElement {
  public static void main(String args[]) {
    Deque<String> dq = new LinkedList<String>();
    dq.add("He");
    dq.add("is ");
    dq.add("a");
    dq.add("boy");
    System.out.println("Is Deque empty : " + dq.isEmpty());
    System.out.println("Elements of Deque = " + dq);
    System.out.println("Size of Deque : " + dq.size());
    Object obj = dq.element();
    System.out.println("Element at head position = " + obj);
    Iterator<String> idq = dq.iterator();
    while (idq.hasNext()) {
      dq.remove();
    }
    System.out.println("Is Deque empty : " + dq.isEmpty());
    // Here the implementation of element() method will display exception
    System.out.println(dq.element());
  }
}

Output :

Is Deque empty : false

Elements of Deque = [He, is , a, boy]

Size of Deque : 4

Element at head position = He

Is Deque empty : true

Exception in thread "main" java.util.NoSuchElementException

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

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

at devmanuals.com.DequeElement.main(DequeElement.java:25)

Download Source code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics