Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java provides two methods to remove element from Queue?

Tags:

java

queue

The Queue implementation in Java has two methods to remove element, One is remove() which throws exception and other one is poll() which returns null for an empty queue. I have two doubts:

  1. Why Queue has different implementation to remove element?
  2. Which implementation to use When?
like image 568
munish Avatar asked Feb 03 '10 16:02

munish


People also ask

What method is used to remove and element from a queue?

The queue. remove() function in Java returns the element available at the front of the queue and removes that element from the queue.

What is the method used in Java to remove and element from a queue?

Queue remove() method in Java The remove() method of Queue Interface returns and removes the element at the front of the container. It deletes the head of the container. The method throws an NoSuchElementException when the Queue is empty.

What is the difference between poll () and remove () method of queue interface?

The remove() and poll() methods differ only in their behavior when the queue is empty: the remove() method throws an exception, while the poll() method returns null. The element() and peek() methods return, but do not remove, the head of the queue.

Can you remove a specific element from a queue Java?

You could use the method: remove(Object o) Removes the first occurrence of the specified element from this list, if it is present. If this list does not contain the element, it is unchanged.


2 Answers

In some situations it's expected that a queue will be empty, and in those cases having a method that doesn't throw an exception is appropriate. In other situations it's an exceptional circumstance that the queue is empty, and an exception is appropriate.

Throwing exceptions incurs a performance penalty, and if it's the case that you expect the queue to be empty from time to time you don't want to have to handle the queue-empty-logic as catching an exception -- it's both costly and difficult to read.

In the opposite case where you don't expect the queue to ever be empty it is a sign of a programming error, or some other exceptional circumstance that it is, and you don't want to write ugly error condition checking code (e.g. checking for null), because in this case that would be less readable than catching an exception (which you can do in another scope).

like image 167
Theo Avatar answered Oct 14 '22 18:10

Theo


The abstract class AbstractQueue<E> implements Queue<E> and define the remove method.

You can take a look at source code:

public E remove() {     E x = poll();     if (x != null)         return x;     else         throw new NoSuchElementException(); } 

So, as you can see, the remove() method use poll() method.

You can use which one you prefer.

like image 31
Massimo Fazzolari Avatar answered Oct 14 '22 19:10

Massimo Fazzolari