调整 Java 中具有相同名称的数组的大小

Resize an Array in Java with same name

我正在尝试将数组的大小调整为我的 'push' 方法,但在输出中没有数字“6”。

有线索吗?

public void push(int value) {
        if (size != maxSize){ 
            top++;
            stackArray[top] = value;
            size++;
        }else if (size == maxSize){
            stackArray = Arrays.copyOf(stackArray, size * 2);
            maxSize = size * 2;
            size++;
        }else{
            throw new RuntimeException();
        }
    }

弹出方法

public int pop() {
        if (size != 0){
            size--;
            return stackArray[top--];
        } else {
            throw new RuntimeException();
        }
    }

我把一些元素放在那个堆栈上

Stack theStack= new Stack(5);

    theStack.push(1);
    theStack.push(2);
    theStack.push(3);
    theStack.push(4);
    theStack.push(5);
    theStack.push(6);
    theStack.push(7);

    System.out.println(theStack.pop());
    System.out.println(theStack.pop());
    System.out.println(theStack.pop());
    System.out.println(theStack.pop());
    System.out.println(theStack.pop());
    System.out.println(theStack.pop());

然后我得到了这个

7 5个 4个 3个 2个 1

size == maxSize 的情况下,调整数组大小后不添加 6。请将您的方法修改为类似这样的内容。

现在,您首先调整大小(如果需要)。然后正常插入。

public void push(int value) {
    // resize if required
    if (size == maxSize){
        stackArray = Arrays.copyOf(stackArray, size * 2);
        maxSize = size * 2;
    }

    // then do the addition to the array stuff
    if (size != maxSize){ 
        top++;
        stackArray[top] = value;
        size++;
    } else {
        throw new RuntimeException();
    }
}