Search code examples
javaoop

Why Stack extends Vector in JDK?


Stack is not a Vector then why Stack class is extending(is a relationship) Vector class in JDK, Stack suppose to work with push() & pop() operations, but because it extends Vector I am able to do add() and remove() operations over a stack.

I think rather extending Vector class, Stack class should use Vector class as a composition.


Solution

  • Outmoded classes

    Both Stack and Vector were included with the first release of Java. Java was rushed to market ahead of its time because of the Internet frenzy at that time.

    Some of the classes bundled with those earliest versions of Java, such as the date-time classes, were not well thought-out. They had not been subjected to peer review and public scrutiny as were later libraries such as some produced through the Java Community Process and through open-source projects and industry consortium projects.

    Java Collections framework

    The Java Collections framework supplants both of these classes. Similarly, the java.time framework supplants the old date-time classes such as java.util.Date/.Calendar. The old classes remain in Java for backwards compatibility with existing apps but should not be used in new code.

    Legacy Modern replacement
    Vector List such as ArrayList
    Stack Deque such as ArrayDeque & LinkedList

    The Stack class documentation tells you this, clearly saying you should instead be using an implementation of the Deque interface.

    diagram of classes in the Java Collections Framework

    Diagram is by Ramlmn, published on Wikipedia. Modified by me to indicate Vector & Stack being obsolete.

    Update: Java 21 brought sequenced collections, adding more interfaces than seen in the chart above. See JEP 431: Sequenced Collections.

    Java Collections interface hierarchy including sequenced collections

    Third-parties have created more collections interfaces and implementations: