Java implementation stack (can be put in infinity)

Source: Internet
Author: User
Tags array length

Always want to use Java to implement the stack, queue, but no time, immediately to find an internship, on the review of the algorithm, to achieve a simple stack, the code is still problematic, interested brothers help correct

  Problem: Multi-threaded words pop and push can only have one method to be executed need to add mutex variable


Importjava.util.Arrays; Public classStack<item> {    Private transientobject[] data;//Storing Data    Private intTop//represents the top element of the stack    Private intoldcapacity;  PublicStack () {oldcapacity= 100; Data=NewObject[oldcapacity];//need to expand to re-build the array, copy this to the pasttop =-1; }     Public synchronized voidPut (Item t) {//Press Stack        if(Top >oldcapacity-2) {            intNewcapacity = (oldcapacity * 3)/2 + 1;//imitate ArrayList to increase the length of array lengthOldcapacity =newcapacity; Data=arrays.copyof (data, newcapacity); } Top++; Data[top]=T; }     Public synchronizedItem Pop () {//out of the stack        if(Top < 0) {            return NULL; } Item T=(Item) data[top]; Top--; returnT; }}

Java implementation stack (can be put in infinity)

Related Article

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: 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.