In this section we will discuss how can element( ) method be implemented in Queue interface in java.
element( ) method of Queue Interface in Java.
In this section we will discuss how can element( ) method be implemented in Queue interface in java.
Syntax
E element( )
This method returns an element at the top position of the queue.
In this method you can retrieve the element at the top of the queue. This method returns the element, but does not remove at the head of the underlying queue. It displays 'NoSuchElementException' exception if queue is empty.
Parameter description
This method does not take any argument but, it returns the element at the head position of the queue.
Example of element( ) method
In this example we will show you, how does element( ) method work in Queue interface. This Example will help you to understand how can you find element at the top position of the queue. Through this example we will show you how you can be retrieve the element at the head position of the underlying Queue, and count the total number of elements in queue. We also show what the exception will display through this method.
Example :
package devmanuals.com; import java.util.Queue; import java.util.LinkedList; import java.util.Iterator; public class QueueElement { public static void main(String args[]) { Queue<Integer> q = new LinkedList<Integer>(); q.add(1); q.add(2); q.add(3); q.add(4); q.add(5); System.out.println("Is Queue empty : " + q.isEmpty()); System.out.println("Elements of queue = " + q); System.out.println("Size of Queue : " + q.size()); Object obj = q.element(); System.out.println("Element at head position = " + obj); Iterator iq = q.iterator(); while (iq.hasNext()) { q.remove(); } System.out.println("Is Queue empty : "+q.isEmpty()); // Here the implementation of element() method will display exception System.out.println(q.element()); } }
Output :
Is Queue empty : false Elements of queue = [1, 2, 3, 4, 5] Size of Queue : 5 Element at head position = 1 Is Queue empty : true Exception in thread "main" java.util.NoSuchElementExceptionat java.util.LinkedList.getFirst(Unknown Source) at java.util.LinkedList.element(Unknown Source) at devmanuals.com.QueueElement.main( QueueElement.java:25) |
[ 0 ] Comments