Skip to content

Instantly share code, notes, and snippets.

@Juliet-Selebalo
Forked from Apondi/StackImpl.java
Created May 31, 2018 09:09
Show Gist options
  • Save Juliet-Selebalo/e632859eb35fe0ee04c40c267643aa85 to your computer and use it in GitHub Desktop.
Save Juliet-Selebalo/e632859eb35fe0ee04c40c267643aa85 to your computer and use it in GitHub Desktop.
Implementation of a Java stack
package stack;
/**
*
* @author kevi
* @param <T>
*/
public class StackImpl<T> implements Stack<T>{
private T[] data;
private int capacity;
private int currentItem = 0;
StackImpl(int size){
this.capacity = size;
this.data = (T[]) new Object[size];
}
//the base data structure
@Override
public boolean empty() {
return data.length == 0;
}
@Override
public void pop() {
//go to the last object in the array
//remove it
if(!(empty())){
data[currentItem] = null;
currentItem--;
} else {
System.out.println("Empty stack, you can add items now");
}
}
@Override
public void push(T item) {
if(currentItem <= capacity){
data[currentItem] = item;
currentItem++;
} else {
//expand the capacity of the bag
expand();
data[currentItem] = item;
currentItem++;
}
}
@Override
public void peek() {
System.out.println(data[currentItem]);
}
//search for the occurance of the item
//if present return the index
//if absent return -1
@Override
public int search(T item) {
for(int i = 0; i< data.length; i++){
if(data[i].equals(item)){
return i;
}
}
return -1;
}
private void expand() {
T[] tempArray = (T[]) new Object[data.length + data.length];
for(int i = 0; i < data.length; i++)
tempArray[i] = data[i];
this.data = tempArray;
}
}
@Juliet-Selebalo
Copy link
Author

suggestion: expand could take in a number (how many more elements do you want to add, let's call it additionalLength) then the tempArray length is data.length + additionalLength.

So you have:
T[] tempArray = (T[]) new Object [data.length + additionalLength]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment