我需要一个堆栈数据结构为我的用例。我应该能够将项目推入数据结构,我只想从堆栈中检索最后一项。JavaDoc for Stack说:
一个更完整和一致的后进先出堆栈操作集是
由Deque接口及其实现提供,这应该
优先用于该类。例如:
Deque<Integer> stack = new ArrayDeque<>();
我肯定不希望在这里使用同步行为,因为我将在方法的本地使用这个数据结构。除此之外,为什么我更喜欢Deque而不是Stack呢?
附:Deque的javadoc说:
Deques也可以用作后进先出(LIFO)堆栈。这
接口应该优先于遗留的Stack类。
下面是Deque优于Stack的几个原因:
Object oriented design - Inheritance, abstraction, classes and interfaces: Stack is a class, Deque is an interface. Only one class can be extended, whereas any number of interfaces can be implemented by a single class in Java (multiple inheritance of type). Using the Deque interface removes the dependency on the concrete Stack class and its ancestors and gives you more flexibility, e.g. the freedom to extend a different class or swap out different implementations of Deque (like LinkedList, ArrayDeque).
不一致性:Stack扩展了Vector类,允许您通过索引访问元素。这与Stack应该做的事情不一致,这就是为什么Deque接口是首选的(它不允许这样的操作)——它允许的操作与FIFO或LIFO数据结构应该允许的操作一致。
性能:Stack扩展的Vector类基本上是ArrayList的“线程安全”版本。同步可能会对应用程序造成严重的性能影响。此外,扩展其他类使用不需要的功能(如第2条所述)会使对象膨胀,可能会消耗大量额外的内存和性能开销。