Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the legacy Stack with what from Java Collections?

This is kind of a Java trivia question perhaps.

I have used the Stack implementation many times.

I have read that this is considered a legacy class and due to the fact that it subclasses Vector makes its performance bad in single threaded applications.

My question is, what is the best alternative among the Java Collection classes?

Is there another Stack class available (by a different name perhaps) that is the one to choose?

I mean, ok implementing a stack arround another existing data structure is easy, but I would expect there is an existing Stack to use.

like image 729
Cratylus Avatar asked Nov 26 '11 21:11

Cratylus


People also ask

What can I use instead of Java stack?

Use ArrayDeque Instead of Stack Instead, use the ArrayDeque class (implements the Deque interface) to implement the stack data structure in Java.

What are legacy collections in Java?

Legacy classes and interfaces are the classes and interfaces that formed the collections framework in the earlier versions of Java and how now been restructured or re-engineered. They are fully compatible with the framework. Formally are not deprecated. All legacy classes were re-engineered to support generic in JDK5.

What are legacy classes and interfaces present in collections?

The Legacy classes are synchronized as opposed to the classes in the collection framework. The Legacy classes are Dictionary, Hashtable, Properties, Stack, and Vector. The Legacy interface is the Enumeration interface.


2 Answers

If you read a more current Javadoc (1.6 or 1.7 for example) rather than the old 1.4.2 docs, you'll find:

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

http://docs.oracle.com/javase/6/docs/api/java/util/Stack.html http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

like image 93
Brian Roach Avatar answered Sep 24 '22 00:09

Brian Roach


In Java7, you can use

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#asLifoQueue(java.util.Deque)

to get a Stack-like object. add() works like push() and remove() works like pop(), etc. I'm answering here long after the question was asked because this seems to be the new 'right' answer for this.

like image 40
JVMATL Avatar answered Sep 23 '22 00:09

JVMATL