堆栈推送时的超出界限异常

Ahm*_*ama 8 java arrays data-structures

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

lea*_*iro 7

当值为this.size"正确" 时,您需要初始化数组.最初的值this.size0(零)(参见变量的初始值),所以这不是初始化数组的时间; 你必须"等待"才能知道阵列的大小.提供那么大小的?在类构造函数中.

所以它在构造函数中必须初始化数组(使用提供的大小).

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

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" any value in it)
    public int top = -1;

    //Methods
    public void push(int value)
    {
        top++;             // after this line `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
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,为了解决这个问题,你需要改变你的代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)