Java Stack Class
A stack is a subclass of Vector that implements a standard last-in-first-out (LIFO) stack.
The stack defines only a default constructor used to create an empty stack. In addition to all the methods defined by Vector, the stack also defines some of its own methods.
Stack()
In addition to all the methods defined by Vector, it also defines some of its own methods:
| No. | Method Description |
|---|---|
| 1 | boolean empty() |
| Tests whether the stack is empty. | |
| 2 | Object peek( ) |
| Looks at the object at the top of the stack without removing it from the stack. | |
| 3 | Object pop( ) |
| Removes the object at the top of the stack and returns that object as the value of this function. | |
| 4 | Object push(Object element) |
| Pushes an item onto the top of the stack. | |
| 5 | int search(Object element) |
| Returns the position of the object in the stack, based from 1. |
Example
The following program demonstrates several of the methods supported by this collection
Example
import
java
.
util
.*;
public
class
StackDemo
{
static
void
showpush
(
Stack
<
Integer
st
,
int
a
)
{
st
.
push
(
new
Integer
(
a
)
)
;
System
.
out
.
println
(
"
push(
"
a
"
)
"
)
;
System
.
out
.
println
(
"
stack:
"
st
)
;
}
static
void
showpop
(
Stack
<
Integer
st
)
{
System
.
out
.
(
"
pop ->
"
)
;
Integer
a
=
(
Integer
)
st
.
pop
(
)
;
System
.
out
.
println
(
a
)
;
System
.
out
.
println
(
"
stack:
"
st
)
;
}
public
static
void
main
(
String
args
[
]
)
{
Stack
<
Integer
st
=
new
Stack
<
Integer
(
)
;
System
.
out
.
println
(
"
stack:
"
st
)
;
showpush
(
st
,
42
)
;
showpush
(
st
,
66
)
;
showpush
(
st
,
99
)
;
showpop
(
st
)
;
showpop
(
st
)
;
showpop
(
st
)
;
try
{
showpop
(
st
)
;
}
catch
(
EmptyStackException
e
)
{
System
.
out
.
println
(
"
empty stack
"
)
;
}
}
}
The compilation and execution results of the above example are as follows:
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack