I'm studying stacks. I was trying to write my code for pop() when I encountered that Java doesn't allow to "convert from null to int"...
How can I remove an element from array? Even if I typecast null to integer, it throws a null pointer exception.
Most other tutorials I've seen online just change the top of stack and do nothing about the value at the index.
Check the int pop() function below
static class Stack{
int[] holder;
int capacity;
int top;
//Constructor
Stack(int a){
holder = new int[a];
capacity = a-1;
top = -1;
}
//Method to Print Stack
void PrintStack(){
System.out.println(Arrays.toString(this.holder));
}
//Method to PUSH
void push(int a){
//Check for StackOverflow
if(top == capacity){
System.out.println("Stack Overflow!!!");
}
else{
top++;
this.holder[top] = a;
}
}
//Method to POP
int pop(){
//Check for StackUnderflow
if(top == -1){
System.out.println("Stack Underflow");
}
else{
return this.holder[top];
this.holder[top] = null;
top--;
}
}
}