Java Reference
In-Depth Information
Stack: [Ken, Donna, Richard, John]
Element at top: Ken
Popped: Ken
Stack: [Donna, Richard, John]
Element at top: Donna
Popped: Donna
Stack: [Richard, John]
Element at top: Richard
Popped: Richard
Stack: [John]
Element at top: John
Popped: John
Stack: []
Stack is empty: true
Note that even if the
Deque
provides all the methods that you need to use it as a stack, it does not give a
programmer a collection type that can be truly used as a stack. If you need a stack in a method as its argument, you
will need to declare it as a
Deque
type as shown:
public class MyClass {
public void myMethod(Deque stack){
/* This method is free to use (or misuse) stack argument
as a FIFO even though it needs only a LIFO queue
*/
}
}
The
myMethod()
is passed a
Deque
when it needs a stack. If you trust
myMethod()
, it's fine. Otherwise, it can access
elements of the
Deque
in any way the
Deque
interface allows. It is not limited to use only as a stack. The only way you
can stop the user of your
Deque
to use it only as a stack is to roll out your own interface and an implementation class.
The
Stack
class works as a stack. However, you are advised not to use the
Stack
class to work with a stack as it has the
same problem that you are trying to solve.
You can create an interface named
LIFOQueue
with four methods:
isEmpty()
,
push()
,
pop()
, and
peek()
. You
can create an implementation class named
ArrayLIFOQueue
, which implements the
LIFOQueue
interface. Your
ArrayLIFOQueue
class will wrap an
ArrayDeque
object. All of its methods will be delegated to
ArrayDeque
. And that is
all. Note that by creating a new
LIFOQueue
interface and its implementation, you are diverting from the Collections
Framework. Your new interface and classes will be outside the Collections Framework. However, if you do need to
implement your own version of a data structure that can be used strictly as a stack, you can do so.
There is another way to create a stack from a
Deque
. You can convert a
Deque
to a
LIFO Queue
using the
asLifoQueue()
static method of the
Collections
class. The method signature is as follows:
•
public static <T> Queue<T> asLifoQueue(Deque<T> deque)
The following snippet of code creates a stack from a
Deque
:
Deque<String> deque = create a Deque ;
// Get a LIFO queue from Deque
Queue<String> stack = Collections.asLifoQueue(deque);
// Now, you can pass around stack reference, which can be used only as a LIFO queue