Created
April 29, 2014 01:47
-
-
Save mcrumm/11388910 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//stack.ArrayStack | |
//Michael Crumm 2010-10-04 | |
package stack; | |
//An ArrayStack uses an internal Object array to store elements. | |
public class ArrayStack implements Stack | |
{ | |
private int size = 0; | |
private Object[] element; | |
//Initialize an ArrayStack of size 100 | |
public ArrayStack() | |
{ | |
this(100); | |
} | |
//Initialize an ArrayStack of size theSize | |
public ArrayStack(int theSize) | |
{ | |
this.element = new Object[theSize]; | |
} | |
//post: returns number of elements in this stack | |
public int size() | |
{ | |
return this.size; | |
} | |
//post: returns true if this stack is empty | |
public boolean isEmpty() | |
{ | |
if (this.size() > 0) { | |
return false; | |
} else { | |
return true; | |
} | |
} | |
//post: theElement is added to the top of this stack | |
public void push(Object theElement) | |
{ | |
if(this.element.length == this.size) { | |
doubleArrayCapacity(); | |
} | |
this.element[this.size] = theElement; | |
this.size++; | |
} | |
//pre: stack not empty | |
//post: removes top element and returns it | |
public Object pop() | |
{ | |
if(this.isEmpty()) { | |
throw new StackEmptyException("Could not pop."); | |
} | |
this.size--; | |
Object removedElement = this.element[this.size]; | |
this.element[this.size] = null; | |
return removedElement; | |
} | |
//pre: stack not empty | |
//post: returns the top element | |
public Object peek() | |
{ | |
if(this.isEmpty()) { | |
throw new StackEmptyException("Could not peek."); | |
} | |
return this.element[(this.size-1)]; | |
} | |
//returns a String representation of the ArrayStack | |
public String toString() | |
{ | |
String retval = ""; | |
String sep = ""; | |
int count = this.size-1; | |
while(count >= 0) { | |
retval += sep + this.element[count].toString(); | |
sep = ","; | |
count--; | |
} | |
return retval; | |
} | |
//doubles size of this.element while retaining its data | |
private void doubleArrayCapacity() | |
{ | |
Object[] bigArray = new Object[2*this.size]; | |
int count = 0; | |
while(count < this.size) { | |
bigArray[count] = this.element[count]; | |
count++; | |
} | |
this.element = bigArray; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment