I am trying to implement stack using array as its core in Java. This is just the purpose of learning and understanding how stack works.
My idea was to use Array (not ArrayList) and tried to mimic the Stack structure. This implementation will have a static size. There is a pointer that starts with -1 to indicate empty stack. The pointer will increment as we add element, and we don't have to worry about deleting the element because we will override the value once we need that space (index).
The following will be my source code and follow by some questions:
import java.util.*;
public class stackUsingArray{
private int[] myStack;
private int pointer;
/**
-Constructor
*/
public stackUsingArray()
{
myStack = new int[10];
pointer = -1;//keep track of where the top element is on the stack.
}
/**
-Pop method
*/
public int pop()
{
if(pointer==-1)
{
//throw exception here
}
return myStack[pointer--];
}
/**
-Push when the stack is not empty.
*/
public void push(int num)
{
if(pointer== myStack.size()-1)
{
//throw exception here
}
else
{
myStack[++pointer] = num;//add to the stack
}
}
/**
-return the top element of the stack
*/
public void peek()
{
return pointer;
}
/**
-return false if there is not more element on the stack
*/
public boolean isEmpty()
{
return (pointer == -1)? true : false;
}
public static void main(String [] arg)
{
stackUsingArray newStack = new stackUsingArray();
newStack.push(1);
newStack.push(2);
newStack.push(3);
System.out.println(newStack.pop());
}
}
At the part where I comment as throw exception:
public int pop()
{
if(pointer==-1)
{
//throw exception here
}
return myStack[pointer--];
}
What kind of exception do you think will the most logical? Most of the time, I just printout on the screen. However, I would love to learn how to throw exception.
This part:
public void push(int num)
{
if(pointer== myStack.size()-1)
{
//throw exception here
}
else
{
myStack[++pointer] = num;//add to the stack
}
}
The program itself has to do the operation of myStack.size() -1 . I wonder if it is better to have a private member in the class to hold the size -1? I mean in turn of efficiency.
Also, if we were to use ArrayList to implement this Stack. Will it run more efficiently? I mean, ArrayList has a lot of overhead such as internal call of methods.
Lastly, I know my code is not great, so please give me some advice to make it better!