0% found this document useful (0 votes)
5 views1 page

Java Stack Implementation Example

The document contains a Java implementation of a Stack class with methods to push and pop objects. It includes a dynamic array to hold elements and ensures capacity is managed when the stack is full. The main method demonstrates creating a Stack instance with an initial capacity of 100.

Uploaded by

r.lhb.9017
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

Java Stack Implementation Example

The document contains a Java implementation of a Stack class with methods to push and pop objects. It includes a dynamic array to hold elements and ensures capacity is managed when the stack is full. The main method demonstrates creating a Stack instance with an initial capacity of 100.

Uploaded by

r.lhb.9017
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

publicclass Stack {

//keep these two fields as they are


private Object[] elements;
private int size =0;

public Stack(int initialCapacity){


elements = new Object[initialCapacity];
}

publicvoid push(Object object){


ensureCapacity();
elements[size++] = object;
}

public Object pop(){


if(size == 0){
thrownewEmptyStackException();
}
returnelements[--size];
}

private void ensure Capacity(){


if([Link] == size){
Object[] old = elements;
elements= new Object[2* size +1];
[Link](old, 0, elements, 0, size);
}
}

publicstaticvoid main(String args[]){

Stack stack= newStack(100);


}

You might also like