Replace the legacy Stack with what from Java Colle

2019-06-17 06:03发布

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.

6条回答
神经病院院长
2楼-- · 2019-06-17 06:37

From the Stack javadoc:

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.

Deque stack = new ArrayDeque();

查看更多
成全新的幸福
3楼-- · 2019-06-17 06:39

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

查看更多
该账号已被封号
4楼-- · 2019-06-17 06:46

You can use a Deque to add and remove things from the same end.

查看更多
倾城 Initia
5楼-- · 2019-06-17 06:48

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.

查看更多
成全新的幸福
6楼-- · 2019-06-17 06:52

LinkedList implements push and pop methods. See also other Deque implementations.

Commons Collections implements an ArrayStack class.

查看更多
混吃等死
7楼-- · 2019-06-17 07:00

You can use LinkedList which implements the Deque interface and allows pushing and popping.

查看更多
登录 后发表回答