pop method of
java.util.Stack class, it throws
EmptyStackException if the Stack is empty. But the
remove method (which similar to
Stack class) of
java.util.Queue instead throws
NoSuchElementException. why there is this inconsistency in the JDK implementation?
Stack class is a legacy class from the Java 1.0 days, prior to the introduction of the collections framework. It's 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.
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
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
StringBuffer and so on. But once Java 1.1 was released, it was too late.