Here is an example of implementing stack in java (Array Based implementation):
public class MyStack extends Throwable{
/**
*
*/
private static final long serialVersionUID = -4433344892390700337L;
protected static int top = -1;
protected static int capacity;
protected static int size;
public int stackDatas[] = null;
public MyStack(){
stackDatas = new int[10];
capacity = stackDatas.length;
}
public static int size(){
if(top < 0){
size = top + 1;
return size;
}
size = top+1;
return size;
}
public void push(int data){
if(capacity == size()){
System.out.println("no memory");
}else{
stackDatas[++top] = data;
}
}
public boolean topData(){
if(top < 0){
return true;
}else{
System.out.println(stackDatas[top]);
return false;
}
}
public void pop(){
if(top < 0){
System.out.println("stack is empty");
}else{
int temp = stackDatas[top];
stackDatas = ArrayUtils.remove(stackDatas, top--);
System.out.println("poped data---> "+temp);
}
}
public String toString(){
String result = "[";
if(top<0){
return "[]";
}else{
for(int i = 0; i< size(); i++){
result = result + stackDatas[i] +",";
}
}
return result.substring(0, result.lastIndexOf(",")) +"]";
}
}
calling MyStack:
public class CallingMyStack {
public static MyStack ms;
public static void main(String[] args) {
ms = new MyStack();
ms.push(1);
ms.push(2);
ms.push(3);
ms.push(4);
ms.push(5);
ms.push(6);
ms.push(7);
ms.push(8);
ms.push(9);
ms.push(10);
System.out.println("size: "+MyStack.size());
System.out.println("List---> "+ms);
System.out.println("----------");
ms.pop();
ms.pop();
ms.pop();
ms.pop();
System.out.println("List---> "+ms);
System.out.println("size: "+MyStack.size());
}
}
output:
size: 10
List---> [1,2,3,4,5,6,7,8,9,10]
----------
poped data---> 10
poped data---> 9
poped data---> 8
poped data---> 7
List---> [1,2,3,4,5,6]
size: 6