I have started learning data structures and have implemented my own stack implementation:
package com.algo.stack;
import java.io.Serializable;
import java.lang.reflect.Array;
public class MyStack<T extends Serializable> {
private T[] myArray = null; // the array is the stack content
private int arraySize = 0; // holds the size counter
/*
* Initialize stack for its size and generic type
*/
public MyStack(Class<T> c,int stackSize){
@SuppressWarnings("unchecked")
final T[] a = (T[]) Array.newInstance(c , stackSize);
this.myArray = a;
}
/**
* The push method, which adds
* numbers in internal array
* @param obj
* @throws Exception
*/
public void push(T obj) throws Exception{
if(this.arraySize < this.myArray.length){
this.myArray[this.arraySize++] = obj;
}else{
throw new Exception("MyStack is Full, need to pop");
}
}
/**
* pops or removes elements from
* the internal array in LIFO fashion
* @return
* @throws Exception
*/
public T pop() throws Exception{
if(this.arraySize <= 0){
throw new Exception("Nothing to pop, stack is empty");
}
return this.myArray[--this.arraySize];
}
/**
* Returns the total size
* @return
*/
public int size(){
return this.arraySize;
}
public static void main(String[] args){
MyStack<Integer> stack1 = null;
MyStack<String> stack2 = null;
try{
stack1 = new MyStack<Integer>(Integer.class, 3);
stack1.push(12);
stack1.push(24);
stack1.push(36);
while(stack1.size() > 0){
System.out.println(stack1.pop());
}
System.out.println("\n");
stack2 = new MyStack<String>(String.class, 4);
stack2.push("Leo");
stack2.push("Tom");
stack2.push("Nancy");
stack2.push("Julean");
while(stack2.size() > 0){
System.out.println(stack2.pop());
}
}catch(Exception e){
e.printStackTrace();
}
}
}
It's working fine and the output is:
36
24
12
Julean
Nancy
Tom
Leo
Please review my rough implementation and let me know of any flaws and how I can improve.