当我尝试将一个元素推入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" 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;
}
}