【问题标题】:Stack implementation array index out of bound error堆栈实现数组索引越界错误
【发布时间】:2018-01-16 20:40:31
【问题描述】:

我已经创建了一个堆栈。

public class STK {
    static int capacity = 0; 

    STK(int size) {
        capacity = size;
    }

    int stackk[] = new int[capacity];
    int top = 0;

    public void push(int d) {
        if(top < capacity) {
            stackk[top] = d;
            top++;
        } else {
            System.out.println("Overflow");
        }
    } 
}

它的实现

public class BasicStackImplementation {
    public static void main(String[] args) {
        STK mystack = new STK(5);

        mystack.push(51);
        mystack.push(23);
    }
}

当我尝试运行这段代码时,它给出了一个错误

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at STK.push(STK.java:21)
    at BasicStackImplementation.main(BasicStackImplementation.java:6)

【问题讨论】:

标签: java data-structures stack


【解决方案1】:

字段初始化程序在构造函数之前运行。你的代码相当于这个:

static int capacity = 0;
int stackk[]=new int[capacity];
STK(int size)
{
    capacity=size;
}

所以你正在初始化一个空数组。要修复它,只需在构造函数中初始化stackk

int[] stackk;
STK(int size)
{
    capacity = size;
    stackk = new int[capacity];
}

另外,capacity 因实例而异,不应为 static

【讨论】:

  • 或者根本没有capacity字段,改用stackk.length
【解决方案2】:

当你创建你的类时,你将你的类中的数组属性初始化为相等的容量,即 0。所以你的数组被初始化为 0 个元素。

当你调用你的构造函数并设置容量值时,你需要重新初始化你的类数组等于 new int[value]

【讨论】:

    猜你喜欢
    • 2019-07-08
    • 2015-06-14
    • 2021-05-17
    • 2017-07-26
    • 2014-12-05
    • 2014-06-06
    • 2015-03-22
    相关资源
    最近更新 更多