getFirst() method of Deque Interface in Java.

getFirst() method of Deque Interface in Java.


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

E getFirst() This method retrieves the first element from the deque.

getFirst() method of Deque Interface in Java.

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

Syntax

E getFirst()

This method retrieves the first element from the deque.

In this method the top i.e. head position element of  the underlying deque is returned. The element is only retrieved but does not removed by this method. It displays 'NoSuchElementException' exception if deque is empty.

Parameter description

This method has no argument.

Example of getFirst() method

In this example we will show you, how does getFirst() method work in Deque interface. In the following example we will show how you can be retrieve the first element from 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.Iterator;
import java.util.LinkedList;
public class DequeGetFirst {
  public static void main(String args[]) {
  Deque<Integer> dq = new LinkedList<Integer>();
  dq.add(1);
  dq.add(2);
  dq.add(3);
  dq.add(4);
  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.getFirst();
  System.out.println("Element at the first position is : "+obj);
  Iterator it =dq.iterator();
  while(it.hasNext()){
    dq.remove();
  }
  System.out.println("Is Deque empty : " + dq.isEmpty());
  // Here is the implementation of getFirst() method will display exception
  Object obj1=dq.getFirst();
  System.out.println(obj1);
  }
}

Output :

Is Deque empty : false

Elements of Deque = [1, 2, 3, 4]

Size of Deque : 4

Element at the first position is : 1

Is Deque empty : true

Exception in thread "main" java.util.NoSuchElementException

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

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

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics