What is the flaw with the Stack class?

Stack class in Java violates the Liskov Substitution Principle and has some flaws. java.util.Stack is a subclass of java.util.Vector.

There is a flaw in the current stack class and it has become a matter of discussion online among people. Some feel it is a big mistake and should be changed immediately while for some it can be coped with.

Class java.util.Stack is a part of the java.util package and which extends java.util.Vector. It uses inheritance rather than composition and does not completely follow the Stack ADT (abstract data type).

Stack defines methods such as push(), pop(), and peek(). Being a subclass of Vector, it also inherits all the methods that Vector defines.

Stack being subclass of Vector violates the Liskov Substitution Principle.

Stack supports non-stack operations like inserting or deleting elements at any specified location using Vector's insertElementAt or removeElementAt methods.

Stack is a LIFO data structure one can use Vector's removeElement method to remove a specified element from a Stack object without regard to the element's position in the stack.

Normally List, Tree, Set, etc. are represented as interface in collection framework but Stack is a class.

The interface also exposes implementation details such as capacity.


Share on Google+Share on Google+

What is the flaw with the Stack class?

Posted on: September 2, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: What is the flaw with the Stack class?  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
ilhyung cho
June 13, 2014
Stack IsA Vector?

A stack is not a vector. It should not be. It violates the fundamental isA rule in class design in object orientation. I can hardly believe that Java engineers did not know that. That being said, I think it can be an exception for some utility classes like Stack. If you look at Java's collection hierarchy, it starts from the interface Collection, and then interface Set, List, and Queue. If Stack is to fit in the class/interface hierarchy and to meet the isA rule, there is hardly any place that it can fit. I guess Stack being a subclass of Vector is a compromise. Sometimes, we need to bend a rule. There is no rule without an exception.