Java (11) ------- use of the Stack class
Package com. gc. stack;/*** how to use the stack in java. A Stack is a data structure of "first-in-first-out" (LIFO) and can only be inserted at one end (called "Pressure stack ") or delete (called "out-of-stack") data. * in Java, java. util. stack class constructor create object * public class Stack extends vector * constructor: public Stack () Create an empty Stack * 1. public push (item) pushes the item to the top of the stack. its role is the same as addElement (item) * 2. public pop removes the stack top object and returns this object as the function value * 3. public peek () view the stack top object without removing it * 4. public boolean empty () test whether the stack is empty * 5. public int search (Object object) returns the position of the Object in the stack */import java. util. enumeration; import java. util. stack;/*** learn Stack usage * @ author Android General **/public class StackTest {public static void main (String [] args) {// create a Stack object stack Stack = new Stack (); System. out. println ("three elements into the stack: aaaa, bbbb, and cccc"); // press the aaaastack string to the stack. push ("aaaa"); // display all the elements in the stack: printStack (stack); stack. push ("bbbb"); printStack (stack); stack. push ("cccc"); printStack (stack); String s = new String ("aaaa"); System. out. println ("the position of the element aaaa in the stack" + stack. search (s); s = new String ("bbbb"); System. out. println ("position of element bbbb in stack" + stack. search (s); System. out. println ("three elements: aaaa, bbbb, and cccc"); System. out. println ("element" + stack. pop () + "outbound stack"); printStack (stack); System. out. println ("element" + stack. pop () + "outbound stack"); printStack (stack); System. out. println ("element" + stack. pop () + "outbound stack"); printStack (Stack);} private static void printStack (stack) {if (Stack. empty () {System. out. println ("Stack is empty, no element");} else {System. out. print ("elements in the Stack:"); // obtain the Enumeration items = stack. elements (); // display all elements in the enumeration (stack) while (items. hasMoreElements () {System. out. print (items. nextElement () + "") ;}} System. out. println (); // line feed }}
Run the following command:
Reprinted please indicate the source: http://blog.csdn.net/android_jiangjun/article/details/39183891