Java Reference
In-Depth Information
}
Object element = elements[top--];
//
elements[top+1] = null;
return element;
}
public static void main(String[] args)
{
Stack stack = new Stack(2);
stack.push("A");
stack.push("B");
stack.push("C");
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
Listing2-49
describesacollectionknownasa
stack
,adatastructurethatstoresele-
ments in last-in, first-out order. Stacks are useful for remembering things, such as the
instruction to return to when a method stops executing and must return to its caller.
Stack
providesa
push()
methodforpushingarbitraryobjectsontothe
top
ofthe
stack,anda
pop()
methodforpoppingobjectsoffthestack'stopinthereverseorder
to which they were pushed.
After creating a
Stack
object that can store a maximum of two objects,
main()
invokes
push()
three times, to push three
String
objects onto the stack. Because
thestack'sinternalarraycanstoretwoobjectsonly,
push()
outputsanerrormessage
when
main()
tries to push
"C"
.
At this point,
main()
attempts to pop three
Object
s off of the stack, outputting
each object to the standard output device. The first two
pop()
method calls succeed,
butthefinalmethodcallfailsandoutputsanerrormessagebecausethestackisempty
when it is called.
When you run this application, it generates the following output:
stack is full
B
A