What is the use of having element() and remove() in Queue interface when we have peek() and poll()?
I checked the docs and found these methods are present in java 7 also.
The only difference mentioned is that element() and remove() throws an exception for empty queue.
We can manually throw an exception (in case we need that) if the queue is empty.
Was it truly necessary to keep both set of methods for this only difference? And if we start making different methods based on such differences I think java classes and interfaces will get filled with a LOT of methods. And is this a true object oriented style?
EDIT: Just to make my question clear, so I don’t get the same “where you need exception use this, otherwise use that” answers.
What I can’t understand is there are many such methods, where having an extra method with the same difference will be useful. So why its implemented only in some cases and not in others? Why the same principle was not applied overall? I can understand that maybe only the language creators can answer these why. I want to know does this approach tally with OOPs principles?
Was it necessary? …Possibly. Maybe, maybe not.
In general, you should prefer
element()orremove()if the queue should never be empty at this point in the program. That’s part of the general principle of failing fast: if something is wrong, throw an error as soon as possible so it can be debugged. (If your program doesn’t throw up as soon as a bug happens, then it gets significantly harder to trace that bug, because you only find out about it later on at a different place in the stack.)That said, when you don’t know if the queue is empty, and you want to find out, then exceptions have potentially unacceptable overhead, and returning null is probably preferable.
This was clearly a judgement call, and I can imagine that a different decision might have been made, but I think the call that was made is at least justifiable. There are good reasons to prefer
element()topeek()in some cases, and good reasons to preferpeek()toelement()in other cases.In terms of “why is this approach used in some cases and not others”…the answer varies, and it’s always a highly subjective judgement call. In many cases, the JDK frequently returns null on “failure” when null could never be a “positive” answer, and throws exceptions otherwise — for example,
NavigableMap.firstKey()can return null because null is the first key, so it throws aNoSuchElementExceptionon an empty map, whileNavigableMap.firstEntry()returns null on an empty map because there’s no possibility of confusingnullwith a valid return.