Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Stack extends Vector in JDK?

Tags:

java

oop

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.

like image 217
Sanjit Kumar Mishra Avatar asked May 19 '16 05:05

Sanjit Kumar Mishra


People also ask

Does stack extend Vector?

The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack.

Why is Vector deprecated in Java?

This is because Vector synchronizes on each operation and does not synchronize the whole Vector instance itself. This is not desired in real-world applications, where the whole set of operations needs to be synchronized and not individual operations.

What is Java stack and Vector?

Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.

Why vectors are used in Java?

The Vector class is used in Java to store data using the List interface. For instance, a Vector may be used to store a list of products sold at a department store or a list of supplements available at a local drug store.


1 Answers

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.

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.

like image 88
Basil Bourque Avatar answered Sep 28 '22 03:09

Basil Bourque