
The elementmethod on the other hand throws a NoSuchElementException. The only difference is that if the queue is empty, the peekmethod returns a null. So it returns the element at the head of the queue without removing it. Since the queue is empty, this causes a NoSuchElementExceptionĮxception in thread "main" Īt java.base/(LinkedList.java:248)Īt java.base/(LinkedList.java:667)Īt (QueueDemo.java:18) peek.Line 9 uses the element method to retrieve the head of the queue.Line 8 initializes the daysOfTheWeek Queue to a new empty Queue.Since the call at Line 3 does not remove the value, this call also returns Monday Line 5 again uses the element method again to retrieve the head of the queue.Line 3 uses the element method to retrieve the head of the queue, in this case Monday. It does not remove this value from the queue.It throws a NoSuchElementException if the queue is empty. The elementmethod returns the head of the queue but does not remove it from the queue. Line 4 again invokes the poll method which returns a null since the queue is empty.Line 3 uses the poll method to remove the head of the queue, in this case Monday.Lines 2 uses the add method to add the value Monday to the queue.Sample Code: Queue daysOfTheWeek = new LinkedList() The removemethod on the other hand throws a NoSuchElementException. The only difference is that if the queue is empty, the pollmethod returns a null.

So it removes the element at the head of the queue. Output: Exception in thread "main" Īt java.base/(LinkedList.java:274)Īt java.base/(LinkedList.java:689)Īt (QueueDemo.java:11) poll
POLL JAVA QUEUE CODE
Sample Code (Non-empty Queue) Queue daysOfTheWeek = new LinkedList() If the queue is empty, it throws a NoSuchElementException It removes the element at the head of the queue. The removemethods helps removing a value from a Queue.
POLL JAVA QUEUE FULL

It uses the ArrayBlockingQueue implementation and specifies the size as 1 Queue daysOfTheWeek = new ArrayBlockingQueue(1) īoolean added = daysOfTheWeek.add("Monday") However it is evident for the ArrayBlockingQueue implementation which has a capacity restriction.

This behaviour is not evident when you use the LinkedList implementation of a Queue.

