1

Checking out Queue interface in Java here

I got confused by methods definitions :

element() Retrieves, but does not remove, the head of this queue.

is like

peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

I can see that peek returns null if the queue is empty but both actually are defined as

Throws: NoSuchElementException - if this queue is empty

Same applies to remove() and peek();

Is there any goal behind this or it is just a design pitfall ?

2
  • I guess you meant Same applies to remove() and poll() Commented Mar 7, 2016 at 10:24
  • 3
    The answer is in the docs - element: "Retrieves, but does not remove, the head of this queue. This method differs from peek only in that it throws an exception if this queue is empty. " peek doesn't throw an exception. Commented Mar 7, 2016 at 10:24

2 Answers 2

3

Let's clarify things with a table that should answer your question:

+---------+---------------------------+------------------------+
| method  |          action           | throws when not found? |
+---------+---------------------------+------------------------+
| peek    | Retrieves, doesn't remove | NO                     |
| remove  | Retrieves, removes        | YES                    |
| element | Retrieves, doesn't remove | YES                    |                 
+---------+---------------------------+------------------------+

There are methods that returns null when no element is found, others throws an exception.

The are methods that retrieve and don't remove, others retrieve and remove.

Sign up to request clarification or add additional context in comments.

1 Comment

Good answer, but the more detailed explanation is in Javadoc for Queue interface itself. See the link: docs.oracle.com/javase/8/docs/api/java/util/Queue.html
0

The explanation is in java API for interface Queue: here. In short element() thows exception if the queue is empty and peek() returns a special value to indicate that the Queue is empty

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.