【问题标题】:Having trouble with a resizing function调整大小功能遇到问题
【发布时间】:2020-01-11 18:36:34
【问题描述】:

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

线程“主”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();
}

【问题讨论】:

    标签: java arrays resize heap-memory


    【解决方案1】:

    在您的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();
    }
    

    您在返回中无条件地调用resize(),这意味着该方法将递归,直到您尝试为新的b 分配足够的内存时内存不足。你想返回a而不是return resize()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多