アーメドウサマ:
私は、コンストラクタの引数から配列のサイズを取る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);
lealceldeiro:
あなたは、の値が時に配列を初期化する必要がありthis.size
、「正しい」ものです。最初の値がthis.size
ある0
(ゼロ)(参照変数の初期値をこのアレイを初期化する時ではないので)。あなたは配列がありますサイズだかを知るために、「待つ」必要があります。そのサイズが提供される場合?クラスのコンストラクタで。
だから、それはあなたが(提供サイズの)配列を初期化する必要がコンストラクタ内です。
例えば、コメントコード(あなた下記参照)。
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;
}
}