Java Reference
In-Depth Information
This code pushes six strings onto the stack, with the last string ( “Six” ) ending up on
top. You remove elements off the stack by using the pop() method, which pops them off
the top:
String s1 = (String)s.pop();
String s2 = (String)s.pop();
8
This code pops the last two strings off the stack, leaving the first four strings. This code
results in the s1 variable containing the “Six” string and the s2 variable containing the
“Five” string.
If you want to use the top element on the stack without actually popping it off the stack,
you can use the peek() method:
String s3 = (String)s.peek();
This call to peek() returns the “Four” string but leaves the string on the stack. You can
search for an element on the stack by using the search() method:
int i = s.search(“Two”);
The search() method returns the distance from the top of the stack of the element if it is
found, or -1 if not. In this case, the “Two” string is the third element from the top, so the
search() method returns 2 (zero-based).
As in all Java data structures that deal with indexes or lists, the
Stack class reports element positions in a zero-based fashion: The
top element in a stack has a location of 0, the fourth element
down has a location of 3, and so on.
NOTE
The last method defined in the Stack class is empty , which determines whether a stack is
empty:
boolean isEmpty = s.empty();
The Stack class provides the functionality for a common data structure in software
development.
Map
The Map interface defines a framework for implementing a key-mapped data structure , a
place to store objects each referenced by a key. The key serves the same purpose as an
Search WWH ::




Custom Search