为什么要在堆栈上使用Deque? [英] Why should I use Deque over Stack?

查看:170
本文介绍了为什么要在堆栈上使用Deque?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 Stack datastructure作为我的用例。我应该能够将项目推入数据结构,我只想从堆栈中检索最后一个项目。 JavaDoc for Stack 说:


由Deque界面及其实现提供的更完整和一致的LIFO堆栈操作集是
,应该使用
优先于此类。例如:




  Deque< Integer> stack = new ArrayDeque(); 

我绝对不希望在这里同步行为,因为我将使用本地数据结构的方法。除此之外,为什么我应该选择 Deque 超过 Stack 这里?



PS:来自Deque的javadoc说:


Deques也可以用作LIFO(先进先出)堆栈。这个
接口应该优先于旧的Stack类。



解决方案

一方面,在继承方面更为明智。在我看来, Stack 扩展 Vector 的事实真的很奇怪。在Java早期,继承被过度使用的IMO - 属性是另一个例子。



对于我来说,关键词您引用的文档是一致 Deque 公开了一组操作,这些操作全部是关于从集合的开始或结束,迭代等获取/添加/删除项目 - 就是这样。没有办法通过位置访问元素, Stack 公开,因为它是 Vector



哦,还有 Stack 没有接口,所以如果你知道你需要 Stack 操作你最终提交到一个具体的具体类,这通常不是一个好主意。


I need a Stack datastructure for my use case. I should be able to push items into the datastructure and I only want to retrieve the last item from the Stack . The JavaDoc for Stack 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<>();

I definitely do not want synchronized behavior here as I will be using this datastructure local to a method . Apart from this why should I prefer Deque over Stack here ?

P.S: The javadoc from Deque says :

Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy Stack class.

解决方案

For one thing, it's more sensible in terms of inheritance. The fact that Stack extends Vector is really strange, in my view. Early in Java, inheritance was overused IMO - Properties being another example.

For me, the crucial word in the docs you quoted is consistent. Deque exposes a set of operations which is all about being able to fetch/add/remove items from the start or end of a collection, iterate etc - and that's it. There's deliberately no way to access an element by position, which Stack exposes because it's a subclass of Vector.

Oh, and also Stack has no interface, so if you know you need Stack operations you end up committing to a specific concrete class, which isn't usually a good idea.

这篇关于为什么要在堆栈上使用Deque?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆