简体   繁体   English

从Collections.asLifoQueue(Deque)返回的队列与堆栈(Java 6)之间的区别

[英]Difference between Queue returned from Collections.asLifoQueue(Deque) and a Stack (Java 6)

As part of java 6 a asLifoQueue(Deque) static method is added in Collections utility class. 作为Java 6的一部分,在Collections实用程序类中添加了一个asLifoQueue(Deque)静态方法。

Javadoc says Javadoc说

public static <T> Queue<T> asLifoQueue(Deque<T> deque)

Returns a view of a Deque as a Last-in-first-out (Lifo) Queue. 返回一个双端队列的视图作为后进先出(Lifo)队列。 Method add is mapped to push, remove is mapped to pop and so on. 方法add映射为push,remove映射为pop等。 This view can be useful when you would like to use a method requiring a Queue but you need Lifo ordering. 当您想使用需要Queue但需要Lifo排序的方法时,此视图很有用。

Each method invocation on the queue returned by this method results in exactly one method invocation on the backing deque, with one exception. 此方法返回的队列上的每个方法调用都会在后备双端队列上恰好产生一个方法调用,但有一个例外。 The addAll method is implemented as a sequence of addFirst invocations on the backing deque. addAll方法作为对后备双端队列的addFirst调用序列实现。

Now what is the difference between this and stack. 现在,这和堆栈有什么区别。 Isn't this essentially a stack? 这本质上不是堆栈吗?

堆栈是lifo集合,但(i)它已过时(javadoc建议使用Deque),并且(ii)它不实现Queue接口。

This view can be useful when you would like to use a method requiring a Queue but you need Lifo ordering. 当您想使用需要Queue但需要Lifo排序的方法时,此视图很有用。

The method just wrap the deque argument, so the you can work on an Queue implementations. 该方法只包装了双端队列参数,因此您可以使用Queue实现。 As you say, the queue is just a stack, but the javadoc of the Stack class say: 如您所说,队列只是一个堆栈,但是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接口及其实现提供了一组更完整和一致的LIFO堆栈操作,应优先使用此类。 For example: 例如:

  Deque<Integer> stack = new ArrayDeque<Integer>(); 

Deque is just more complete than Stack and the method asLifoQueue is just an utility to convert a deque to a stack-like data structure. DequeStack更完整, asLifoQueue方法只是将双端队列转换为类似堆栈的数据结构的实用程序。

From Javadoc: 从Javadoc:

When a stack is first created, it contains no items. 首次创建堆栈时,它不包含任何项目。

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接口及其实现提供了一组更完整和一致的LIFO堆栈操作,应优先使用此类。

So it's the same behavior but Deque has more methods to play with 所以这是相同的行为,但是Deque有更多方法可以使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM