Reputation: 1425
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--;
}
}
}
Upvotes: 0
Views: 1094
Reputation: 34628
Since this is an array of (primitive) integers, you cannot assign null
to an element in it. In fact, when the array is created, its elements are not null
, they are set to zero which is the default initial value for an integer.
If the array was an array of objects, it would have been important to replace popped elements with null, otherwise the objects would not be garbage-collected. That problem does not exist when the array is of a primitive type, so you can just leave the value as is.
However, I would advise you to change your array-printing method, because whatever the current size of the stack, it always prints the entire array. That would be confusing. You should print the array only up to the "top" element.
Upvotes: 1
Reputation: 4676
I think the following might be more an accurate way of representing what you're trying to accomplish. Convert int
to an Integer
and return null which is now allowed because it's an Integer type.
public class Stack{
Integer[] holder;
int capacity;
int top;
//Constructor
Stack(int a){
holder = new Integer[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
Integer pop(){
//Check for StackUnderflow
if(top == -1){
return null;
}
else{
return this.holder[top--];
}
}
}
Upvotes: 1
Reputation: 17630
If you want to represent null
in an array of integers, use the java Integer
type, not the native int
type.
It's not terrible to leave the old value in unused spots in your stack. It used to be that there was no distinction between the number zero and a null value, so there was no advantage to modifying values in unused slots.
Upvotes: 1