LoginSignup
0
0

多次元配列の拡張for文

Last updated at Posted at 2024-04-15

多次元配列でforをネストして値を取り出す

下記のような2次元配があるとして…

//classとmainメソッドは省略
    
    int[][] numbers2d = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };

for文で値を取得

        //for文
        for (int i = 0; i < numbers2d.length; i++) { //縦
            for (int j = 0; j < numbers2d[i].length ; j++) { //横
                System.out.print(numbers2d[i][j] + " ");
            }
            System.out.println();
        }

拡張for文で値を取得

・出力の際は「col」のみ書けばいい。numbers2d[col]などとしない。
 col 自体が、number2d配列の縦が詰め込まれたものを意味するから。(ニュアンス)

・内側のfor文は int[] col のような配列ではなく、int col と書く。

        //拡張for文
        for (int[] row : numbers2d ) { //rowに縦の配列を詰めて…
            for (int col : row) { //詰められた配列の要素を順に取り出してcolに一時格納
                System.out.print(col + " ");
            }
            System.out.println();
        }

つまり、
int型の配列rowには
(配列0){1, 2, 3, 4}
(配列1){5, 6, 7, 8}
(配列2){9, 10, 11, 12}
が詰められている。

int型の変数colで、上記それぞれの配列を順に取り出し、
その中でさらに0要素目、1要素目… というように値を取り出していく。

0
0
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
0
0