简体   繁体   English

此代码中Integer.Min_value的用途是什么?

[英]What is the use of Integer.Min_value in this code?

What is the use of Integer.Min_value in this code? 此代码中Integer.Min_value的用途是什么? I know it is dereference S[top] for garbage collection, but need to know more about it 我知道它是对垃圾回收的取消引用S [top],但需要更多了解

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 . top变量应始终是“ last in”堆栈项的索引,在这种情况下, top = 4因为in的最后一个数字为5且索引为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. 这是将S[top]的内容分配给data ,然后将Integer.MIN_VALUE分配给S[top]以“清除”它,然后将top减1。

This line: S[top--] = Integer.MIN_VALUE; 这行: 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 . 执行pop方法后,结果为: S: [ 1, 2, 3, 4, -2147483648 ]top: 3 ,堆栈中的“ last in”项将为4

Hope this makes sense. 希望这是有道理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM