[ACCEPTED]-Why Java provides two methods to remove element from Queue?-queue

Accepted answer
Score: 34

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

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

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

Score: 18

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

You can take a look at 2 source code:

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

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

You can use which one you prefer.

Score: 6

Remove() method differs from poll only in that it 1 throws an exception if this queue is empty.

enter image description here

Score: 5

Looking at the answers, it wasn't clear 5 to me which did what,hence:

Straight from the API : The remove() and 4 poll() methods differ only in their behavior 3 when the queue is empty: the remove() method 2 throws an exception, while the poll() method 1 returns null

Score: 4

When you know how to react right now and/or 2 expect elements to be absent then use poll.

Otherwise 1 use remove.

Score: 1

Sometimes you want a null value returned 3 for an empty queue and sometimes you want 2 it to treat an empty queue as a exception 1 case.

Score: 0

The two methods are used differently in 4 classic discussions about a Queue structure. I 3 use poll() mostly to retrieve items, and 2 remove() mostly if I need to modify the 1 Queue outside of the normal loop.

More Related questions