getLast() method of Deque Interface in Java.

getLast() method of Deque Interface in Java.


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

E getLast() This method finds the last element of the deque.

getLast() method of Deque Interface in Java.

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

Syntax

E getLast()

This method finds the last element of the deque.

In this method the bottom element of deque is returned. Through this method you can only find the element at the last position of the underlying deque but can not deletes that element. It displays 'NoSuchElementException' exception if deque is empty.

Parameter description

This method has no any argument.

Example of getLast() method

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

Example :

package devmanuals.com;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
public class DequeGetLast {
  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.getLast();
  System.out.println("Element at the last position is : "+obj);
  Iterator it =dq.iterator();
  while(it.hasNext()){
    dq.remove();
  }
  System.out.println("Is Deque empty : " + dq.isEmpty());
  // Here is the use of getLast() method will display exception
  Object obj1=dq.getLast();
  System.out.println(obj1);
  }
}

Output :

Is Deque empty : false

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

Size of Deque : 4

Element at the last position is : 4

Is Deque empty : true

Exception in thread "main" java.util.NoSuchElementException

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

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

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics