ImportJava.util.Stack;ImportOrg.junit.Before;Importorg.junit.Test;/*** Stack (stack) inherits the vector class, and the underlying implementation is an array. * Only the methods defined by stack are described here, and the methods in the parent class are no longer described. */ Public classTeststack {//Define a stackStack<string>Stack; @Before Public voidbefore () {//instantiating a stack variablestack =NewStack<string>(); //Add method adds an element to the stack and adds a successful return of trueStack.Add("1"); Stack. Add ("2"); Stack. Add ("3"); Stack. Add ("4"); Stack. Add ("5"); //The push method adds an element to the stack, returning the result as the currently added elementStack.Push("a"); Stack. Push ("B"); Stack. Push (C); Stack. Push ("D"); Stack. Push (E); //both push and add elements are added to the stack, and the underlying implementation is the same, which is to expand the vector first and add } //The pop method removes and returns the top element of the stack, and throws an exception if it is an empty stack: emptystackexception@Test Public voidtest1 () {String pop=stack. Pop (); System.out.println (POP); //eSYSTEM.OUT.PRINTLN (stack);//[1, 2, 3, 4, 5, A, B, C, d] } //The Peek method gets the top element of the stack, but does not remove it, and throws an exception if it is an empty stack: emptystackexception@Test Public voidtest2 () {String peek=stack. Peek (); SYSTEM.OUT.PRINTLN (Peek); //eSYSTEM.OUT.PRINTLN (stack);//[1, 2, 3, 4, 5, A, B, C, D, E] } //Check if stack is empty stack@Test Public voidtest3 () {BooleanIsEmpty =stack. Empty (); System.out.println (IsEmpty); //false } //View the position of an element in the stack, counting from 1 onwards@Test Public voidtest4 () {intindex = stack.Search("1"); SYSTEM.OUT.PRINTLN (index); //Ten }}
Simple use of stack (stack)