Why doesn't Java have an EmptyQueueException?

Hai Hoang :

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?

Stephen C :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35173&siteId=1