Java队列

Java容器主要是一些接口及其实现。

ArrayList和LinkedList类分别是List列表接口的数组实现和链表实现。


Java中队列容器Queue是一个接口,LinkedList实现了此接口,Queue接口窄化了对LinkedList的方法的访问权限。使用时可以利用多态将LinkedList当做队列使用。


import java.util.Queue;
import java.util.LinkedList;
 
Queue queue = new LinkedList(); //queue只能使用Queue接口的方法

Queue方法摘要:

boolean add(E e)  将指定的元素插入此队列

boolean  offer(E e) 将指定元素插入此队列

E element() 获取,但是不移除此队列的头

E remove() 获取并移除此头

E peek() 获取,但是不移除此队列的头,队空返回null

E poll() 获取并移除此队列的头,队空返回null


Queue使用时,尽量使用offer()/poll()/peek()方法。

----------------------------------------------------------------------------------------------------------------------------------

Deque

Deque是Queue的一个子接口。名称 deque 是“double ended queue(双端队列)”的缩写,通常读为“deck”。

此接口定义在双端队列两端访问元素的方法。提供插入、移除和检查元素的方法。每种方法都存在两种形式,一种在操作失败时抛出异常;另一种形式返回一个特殊值(null、false,取决于具体操作)

Queue 方法等效 Deque 方法
add(e)addLast(e)
offer(e)offerLast(e)
remove()removeFirst()
poll()pollFirst()
element()getFirst()
peek()peekFirst()

双端队列也可用作 LIFO(后进先出)堆栈。应优先使用此接口而不是遗留 Stack 类。

原因:

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 consistentDeque 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 Stackexposes 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.

首先,很明显在继承方面,在我看来Stack继承了Vector是真的很奇怪。我觉得,早期的java中,继承被过度使用了。 Properties 是另一个例子。

和文档中你引用的决定性的话是一致的。Deque公开了一组操作,这些操作都是能够在集合的开始或最后fetch/add/remove项,就是这个。有意的没有办法按位置访问元素,因为Stack是Vector的一个子类,所以它会暴露这个元素。

并且,Stack不是接口,所以如果你知道你需要在堆栈操作,你最终提交到一个特定的具体类中,这样是不好的。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值