使用字段值初始化的数组中的ArrayIndexOutOfBoundsException

时间:2018-07-23 20:15:29

标签: java exception data-structures stack

每次我尝试将元素压入堆栈
当我从构造函数中获取数组大小时,这是一个异常,但是当我在声明时分配大小时,它可以正常工作吗?

public class Stack {
    public int size ;
    public Stack(int size)
    {
        this.size = size;
    }
    public int[] arr = new int[size];
    public int top = -1;

    //Methods
    public void push(int value)
    {
        top++;
        arr[top] = value;
    }
}

1 个答案:

答案 0 :(得分:6)

this.size的值是“正确”的值时,您需要初始化数组。最初this.size的值是0(零)(请参阅Initial Values of Variables),所以这不是初始化数组的时间。您必须“等待”才能知道数组的大小。提供该尺寸的地方?在类构造函数中。

因此它位于构造函数内部,您必须在其中初始化数组(具有提供的大小)。

例如,请参见下面的注释代码(您自己):

public class Stack {
    public int size ;                   // size = 0 at this time
    public Stack(int size)
    {
        this.size = size;
    }
    public int[] arr = new int[size];  // still size = 0 at this time!
                                       // so you're creating an array of size zero (you won't be able to "put" eny value in it)
    public int top = -1;

    //Methods
    public void push(int value)
    {
        top++;             // at this time top is 0
        arr[top] = value;  // in an array of zero size you are trying to set in its "zero" position the value of `value`
                          // it's something like this:
                          // imagine this array (with no more room)[], can you put values?, of course not
    }
}

因此,要修复,您需要这样更改代码:

public class Stack {

    public int size;
    public int[] arr;       // declare the array variable, but do not initialize it yet
    public int top = -1;

    public Stack(int size) {
        this.size = size;
        arr = new int[size];  // when we know in advance which will be the size of the array, then initialize it with that size
    }

    //Methods
    public void push(int value) {
        top++;
        arr[top] = value;
    }
}