23
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ポケモン×Java】知識編 配列#3 〜配列を完全攻略! -二次元配列-~

23
Posted at

はじめに

これまで「配列を作って、ぐるぐる回す」ところまでできたね。
次のステップは 二次元配列
表みたいなデータやマップを扱うときにぴったりなんだ。
さらに応用として ジャグ配列(行ごとに列数が違うガタガタな表)もあるよ。


二次元配列ってなに?

二次元配列は「配列の中に配列が入っている」もの。
イメージは 行と列が並んだ表(算数の九九表)。

int[][] table = new int[3][4]; // 3行4列の表
  • 行が3、列が4 → 合計12個の要素(最初は全部0)
  • table[行][列] でアクセスできる

値を入れてみる

int[][] table = new int[3][4];
table[0][0] = 10;
System.out.println(table[0][0]); // 10

イメージ(3行4列)

行\列 0 1 2 3
0 10 0 0 0
1 0 0 0 0
2 0 0 0 0

作り方はいろいろ

① 行と列をまとめて指定(長方形)

int[][] a = new int[3][4];

② 行だけ先に作って、列はあとから

int[][] b = new int[3][]; // 行だけ作る、まだ中身は null
b[0] = new int[4];
b[1] = new int[4];
b[2] = new int[4];

注意! 各行を new する前に要素へアクセスすると NullPointerException(ヌルポインター例外) が出るよ。

③ 中身をリテラルで初期化

int[][] m = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

配列をぜんぶ見るには

二重の for 文を使うよ。

for (int i = 0; i < m.length; i++) {
    for (int j = 0; j < m[i].length; j++) {
        System.out.print(m[i][j] + " ");
    }
    System.out.println();
}

行数 → m.length、その行の列数 → m[i].length


ジャグ配列(行ごとに列数が違う)

行ごとに列数が違う「ガタガタの表」。

int[][] jag = new int[3][];
jag[0] = new int[2];
jag[1] = new int[5];
jag[2] = new int[1];

イメージ

行\列 0 1 2 3 4
0 0 0 / / /
1 0 0 0 0 0
2 0 / / / /

/ を「存在しない部分」として表現してみたよ。

例:月ごとの日数

int[][] days = new int[3][];
days[0] = new int[31]; // 1月
days[1] = new int[28]; // 2月
days[2] = new int[31]; // 3月

ミニ例:ポケモン風マップ

タイルマップ(3行4列)

int[][] tileMap = new int[3][4];
tileMap[0][0] = 1; // 草
tileMap[0][2] = 2; // 水
tileMap[0][3] = 3; // 岩
...

// 作成イメージ
/*
{1, 1, 2, 3}
{1, 2, 2, 3}
{1, 1, 1, 3}
*/

「ポケモンの草むらや水辺をマスで管理するイメージ」

ステージごとの敵数(ジャグ)

int[][] enemies = new int[3][];
enemies[0] = new int[2]; // ステージ1は敵2体
enemies[1] = new int[4]; // ステージ2は敵4体
enemies[2] = new int[1]; // ステージ3は敵1体

よくあるつまずき

  • 各行を初期化しないままアクセス → NullPointerException
  • 添え字を逆に使う (配列[列][行]) → バグのもと
  • ジャグ配列を「列数は固定」と思い込む → 配列[i].length を必ず確認
  • 配列のサイズをあとから変えられると勘違い → 新しい配列を作る必要あり

まとめ

  • 二次元配列は「配列の配列」。
  • 作り方は3つ:①まとめて指定、②あとから列指定、③リテラル初期化。
  • ジャグ配列は「ガタガタの表」を表せる。
  • NullPointerException に気をつけよう!

あとがき

ここまで読んでくれて、本当にありがとうございました。

「プログラミングって難しい…」って思ってた人も、
「ちょっと楽しいかも…!」って思ってもらえたらうれしいな。

次の投稿も、よろしくおねがいします。

💬 コメント・フィードバック歓迎!

「この章わかりやすかった!」
「これ表現まちがってない?」
「次は○○をやってほしい!」などなど、
お気軽にコメントで教えてくださいね!


23
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?