Simple use of stack (stack)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.