Java implements Stack class using a Vector, why ? Though it seems that Arraylist should have been a better choice. Java wanted Stack to be thread safe or is it mandatory for a Stack in general ( Which I don't think is the case ) to be thread safe or there is any other theory for using a Vector to implement a Stack in Java?
-
Possible duplicate of [What are the differences between ArrayList and Vector?](http://stackoverflow.com/questions/2986296/what-are-the-differences-between-arraylist-and-vector) – OneCricketeer Sep 18 '16 at 16:19
-
1Because Stack and Vector were bother introduced in Java at the same time, in JDK 1.0, and ArrayList was introduced long after, in JDK1.2 – JB Nizet Sep 18 '16 at 16:20
2 Answers
Stack
and Vector
were present in JDK 1.0. ArrayList
wasn't added until JDK 1.2. Stack
's inheritance of Vector
is baked into the API, so it's impossible to change now.
But it's an outdated class, anyways. Fixing it isn't a priority. Stack
's own Javadoc writeup says:
A more complete and consistent set of LIFO stack operations is provided by the
Deque
interface and its implementations, which should be used in preference to this class. For example:Deque<Integer> stack = new ArrayDeque<Integer>();

- 1
- 1

- 349,597
- 67
- 533
- 578
I suspect this is just historic. java.util.Stack has been around since Java 1.0 and ArrayList wasn't introduced until 1.2. Vector was all they had at the time to implement it.
Why not change it in 1.2 though? Well, Sun and Oracle have been careful to make Java backwards compatible over time and it would be a breaking change to move from thread-safe to not.

- 22,188
- 6
- 42
- 49