java - 来自用字段值初始化的数组的 ArrayIndexOutOfBoundsException

标签 java arrays data-structures

当我尝试将一个元素放入 Java 数组中时,我从构造函数参数中获取数组大小,它会抛出一个 ArrayIndexOutOfBoundsException 异常。但是,当我在声明添加元素的数组时设置大​​小时有效。

这是我的代码:

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;
    }
}

以下抛出异常:

new Stack(10).push(123);

最佳答案

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" 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
    }
}

因此,为了修复这个问题,您需要像这样更改代码:

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;
    }
}

关于java - 来自用字段值初始化的数组的 ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51486618/

相关文章:

java - 在java中生成序列优惠券代码

java - 在java中使用websocket?

algorithm - 使用 do While 循环反转 LinkedList

python - 将列表映射到霍夫曼树,同时保留相对顺序

java - Java 中 == 和 .equals 的区别。

JavaMail 处理传入消息的读取回执

c++ - 用数组重载运算符 += C++

java - Java 中多维数组的 ClassCastException

php - 遍历 Doctrine 的 changeSet

c# - 比较 C# 中 DateTime 的二进制表示形式