“在函数(isFull())中减去 var 大小是否可以,还是在构造函数中这样做更好?”

" is it ok to subtract the var size in the function(isFull()) or is it better to do that in the constructor?"

 //Constructor
    Cons(size){
    maxsize=size-1;
    }
    //isFull Function
    public boolean isFull(){
            return top==maxsize-1;
        }

但是如果我们尝试将 maxsize 减去一个函数,它会在每次我们 运行 这个函数时改变,所以我们只需要在构造函数中这样做就可以防止 maxsize 得到每次我们 运行 它

时都会减少

maxsize - 1 不会减少 maxsize,它只是计算值。如果你担心计算成本,那么你不应该:)

无论如何,如果大小是固定的,那么你应该在构造函数中进行,以明确

//Constructor
Cons(size){
maxsize=size-1; //maxsize value updated
}

constructor is decreasing maxsize by 1

//isFull Function
public boolean isFull(){
        return top==maxsize-1; //returns true or false and without changing any value
    }

while isFull is only returning the boolean value and not actually subtracting 1 from maxsize

您可以通过执行 isFull 现在正在执行的操作而不是执行以下操作来防止 maxsize 减小

//isFull Function
public boolean isFull(){
        return top==maxsize--; //returns true or false and decreases maxsize by 1        }