调整大小功能有问题

Having trouble with a resizing function

我正在为实验室编写一个调整大小的函数,但我一直收到错误

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

private E[] a, b;  // holds the items
private int N;       // number of items in stack

// create an empty stack with given capacity
public RArrayStack() {
    a = (E[]) new Object[8];
    N = 0;
}

public boolean isEmpty() {
    return N == 0;
}

public boolean isFull() {
    return N == a.length;
}

public void push(E item) {
    if (!this.isFull()) {
        a[N++] = item;

    } else {
        this.resize();
    }
}

public E pop() {
    return a[--N];
}

public E peek() {
    return a[N - 1];
}

public E[] resize(){
        b = (E[]) new Object[a.length*2];
        for (int i = 0; i < a.length ; i++) {
            b[i] = a[i];
        }
        a = b;

    return resize();
}

在您的 resize() 函数中:

public E[] resize(){
        b = (E[]) new Object[a.length*2];
        for (int i = 0; i < a.length ; i++) {
            b[i] = a[i];
        }
        a = b;

    return resize();
}

您在 return 中无条件调用 resize(),这意味着该方法将递归,直到您 运行 内存不足,试图为新 [=13] 分配足够的内存=].而不是 return resize(),你想要 return a