Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Java have an EmptyQueueException? [closed]

Tags:

java

In the pop method of java.util.Stack, it throws an EmptyStackException if the Stack is empty. But the remove method of java.util.Queue (which is similar to pop in the Stack class) instead throws a NoSuchElementException. Why is there this inconsistency in Java?

like image 363
Hai Hoang Avatar asked Nov 30 '18 04:11

Hai Hoang


Video Answer


2 Answers

The Stack class is a legacy class from the Java 1.0 days, prior to the introduction of the collections framework. Its interface has to be backwards compatible ... and that is how it was designed.

By contrast, the Queue interface was introduced in the Java 1.5 revision of the collections framework. By that time, the NoSuchElementException had been chosen by the designers as the best way to express this kind of error condition1.

Note that NoSuchElementException could have been used in Stack since both classes existed in Java 1.0, but clearly, the designers had other ideas back then2.

So this is just a historical anomaly that has arisen due to the way that the Java APIs have evolved. It cannot be fixed without breaking binary compatibility for existing applications that use the Stack class.


1 - You may disagree with that, but you asked why, and this is why.

2 - Or maybe they were just too rushed to get the API design correct. The Java 1.0 release was made under extreme pressure to meet a perceived market opportunity. A few mistakes were made and could not be corrected in time. Other examples include the Enumeration API, the deprecated Thread methods, the Hashtable and Vector classes, StringBuffer and so on. But once Java 1.1 was released, it was too late.

like image 104
Stephen C Avatar answered Oct 22 '22 15:10

Stephen C


The Stack class was there first. In the Javadoc it says "since JDK 1". It defined its own exception type because … it could.

At that same time, the NoSuchElementException already existed, but the Java collections framework didn't exist yet. Therefore it was not yet common to use that exception widely. It was "just one of the predefined exception" types.

The collections framework was added in Java 1.2, and it could not use the StackEmptyException because its name restricts it to be used only with stacks.

At that point, the old Stack class could not be modified anymore since that would have broken existing code. Java has been successful of being backwards compatible over decades, and the exception inconsistency is one sign of this compatibility.


To get an official answer, you could look at the code. It says:

@author Jonathan Payne

If it's really important for you to know, you can contact him directly and ask him whether he remembers what he did 20 years ago. Maybe he does. :)

like image 26
Roland Illig Avatar answered Oct 22 '22 13:10

Roland Illig