调整大小功能时遇到问题

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


线程“main”中的异常 java.lang.OutOfMemoryError:Java 堆空间


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();

}


肥皂起泡泡
浏览 72回答 1
1回答

慕莱坞森

在你的resize()函数中:public E[] resize(){&nbsp; &nbsp; &nbsp; &nbsp; b = (E[]) new Object[a.length*2];&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < a.length ; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; b[i] = a[i];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; a = b;&nbsp; &nbsp; return resize();}您无条件地调用resize()return,这意味着该方法将递归,直到您尝试为 new 分配足够的内存为止b。而不是return resize(),你想返回a
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java