Javaで2次元配列を作成するための構文 質問する

Javaで2次元配列を作成するための構文 質問する

考慮する:

int[][] multD = new int[5][];
multD[0] = new int[10];

これは 5 行 10 列の 2 次元配列を作成する方法ですか?

このコードをオンラインで見ましたが、構文が意味をなさなかったです。

ベストアンサー1

次のことを試してください。

int[][] multi = new int[5][10];

...これは次のようなものの省略形です:

int[][] multi = new int[5][];
multi[0] = new int[10];
multi[1] = new int[10];
multi[2] = new int[10];
multi[3] = new int[10];
multi[4] = new int[10];

intすべての要素は、のデフォルト値に初期化されることに注意してください0。したがって、上記は以下と同等です。

int[][] multi = new int[][] {
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};

...または、もっと簡潔に言えば、

int[][] multi = {
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};

おすすめ記事