What is the use of Integer.Min_value in this code? I know it is dereference S[top] for garbage collection, but need to know more about it
public int pop() throws Exception {
int data;
if (isEmpty())
throw new Exception("Stack is empty.");
data = S[top];
S[top--] = Integer.MIN_VALUE;
return data;
}
Imagine you have a stack defined as an array such as this:
S = [ 1, 2, 3, 4, 5 ]
Stacks are last in, first out. The top variable should always be the index of the "last in" stack item, in this case top = 4
because the last number in is 5
and has an index of 4
.
What this does is assign the content of S[top]
to data
, then assign Integer.MIN_VALUE
to S[top]
to "clear" it, and then decrease top by 1.
This line: S[top--] = Integer.MIN_VALUE;
can be rewritten as the following:
S[top] = Integer.MIN_VALUE; top = top - 1;
I think that the end goal is to clear old values in the stack and give them a default without having to resize the array.
Once the pop method has been executed, here's the result: S: [ 1, 2, 3, 4, -2147483648 ]
and top: 3
and the "last in" item in the stack will be 4
.
Hope this makes sense.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.