Java Reference
In-Depth Information
top = stringStack.pop();
// removes and returns "Jane"
System.out.println(top + " is removed from the stack.");
Parts
a
through
e
of Figure 5-2 show five additions to the stack. At this point, the stack contains—
from top to bottom—the strings
Joe
,
Jane
,
Jill
,
Jess
, and
Jim
. The string at the top of the stack is
Joe
;
peek
retrieves it. The method
pop
retrieves
Joe
again and then removes it (Figure 5-2f ). A subsequent
call to
peek
retrieves
Jane
. Then
pop
retrieves
Jane
and removes it (Figure 5-2g).
Three more calls to
pop
would remove
Jill
,
Jess
, and
Jim
, leaving the stack empty. A subse-
quent call to either
pop
or
peek
would return
null
.
FIGURE 5-2
A stack of strings after (a)
push
adds
Jim
; (b)
push
adds
Jess
;
(c)
push
adds
Jill
; (d)
push
adds
Jane
; (e)
push
adds
Joe
; (f )
pop
retrieves and removes
Joe
; (g)
pop
retrieves and removes
Jane
Joe
Jane
Jane
Jane
Jill
Jess
Jill
Jill
Jill
Jill
Jess
Jess
Jess
Jess
Jess
Jim
Jim
Jim
Jim
Jim
Jim
Jim
(a)
(b)
(c)
(d)
(e)
(f)
(g)
Programming Tip:
Methods such as
peek
and
pop
must behave reasonably when the
stack is empty. Here, we specify that they return
null
. Another possibility is to have them
throw an exception.
Question 1
After the following statements execute, what string is at the top of the stack
and what string is at the bottom?
StackInterface<String> stringStack =
new
OurStack<String>();
stringStack.push("Jim");
stringStack.push("Jess");
stringStack.pop();
stringStack.push("Jill");
stringStack.push("Jane");
stringStack.pop();
Question 2
Consider the stack that was created in Question 1, and define a new empty
stack
nameStack
.
a.
Write a loop that pops the strings from
stringStack
and pushes them onto
nameStack
.
b.
Describe the contents of the stacks
stringStack
and
nameStack
when the loop that you
just wrote completes its execution.