Java implementation of a stack

Source: Internet
Author: User
Tags int size
Package zhangtingting; public class Stacktest {private object[] stack;//number of elements; private int size;///default length to public stacktest () {this (10);}//can also To set its own length, that is, capacity; Public stacktest (int len) {stack = new Object[len];}//returns the number of elements; public int size () {return size;}//Returns the length of the array, that is, the capacity; public int Capacity () {return stack.length;}//implementation dynamic array; public void ensurecapacity () {if (size () = Capacity ()) {object[] newstack = new Object[size () * 3/2 + 1]; System.arraycopy (Stack, 0, newstack, 0, size ()); stack = Newstack; }//into stack; public void push (Object o) {size++; ensurecapacity (); stack[size-1] = o;}//null; public Boolean IsEmpty () {return size = = 0;}//out stack; Public Object Pop () {///first to be empty; if (IsEmpty ()) {throw new ArrayIndexOutOfBoundsException ("cannot be null");} Object o = stack[--size]; Stack[size] = null; return o; public static void Main (string[] args) {stacktest stack = new Stacktest (3); string[] data = new string[] {"A", "B", "C"}; for (int i = 0; i < data.length i++) {Stack.push (data[i]); System.oUt.println (Data[i] + "");} System.out.println ("***********"); while (!stack.isempty ()) {System.out.println (Stack.pop () + "");}    }}

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.