简体   繁体   中英

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.

Javadoc says

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

Returns a view of a Deque as a Last-in-first-out (Lifo) Queue. Method add is mapped to push, remove is mapped to pop and so on. This view can be useful when you would like to use a method requiring a Queue but you need Lifo ordering.

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.

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.

The method just wrap the deque argument, so the you can work on an Queue implementations. As you say, the queue is just a stack, but the javadoc of the Stack class say:

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

From 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.

So it's the same behavior but Deque has more methods to play with

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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