LoginSignup
1
4

More than 3 years have passed since last update.

【Java】二次元配列を拡張for文で回す方法

Posted at

拡張for文

for( 変数名 配列){
}

:の右の配列を左の変数に代入しながらループを回すという手法を組み合わせて二次元配列を展開するにはどうしたら良いか、一瞬迷ったのと、PHPのように

foreach($datas as $key => $value){
 for($i = 0; $i < count($value); i++){
    $value[i] = 0;
  }
}

foreachを使うことも思い浮かべたけど、javaでは別のオブジェクトを生成しないといけないみたいなので、なんとかしたいなと思いました。

拡張forを2回書けば済む話

public class Control {

    public static void main(String[] args) {
        int[][] datas = {
                {0,0,0,0,0,0,0,0,0,0,0},
                {0,0,0,0,0,1,1,1,1,1,0},
                {0,0,0,0,0,0,1,1,1,1,0},
                {0,0,0,0,0,1,1,1,1,1,0},
                {0,0,0,0,1,1,1,1,1,1,0},
                {0,0,0,1,1,1,1,1,0,1,0},
                {0,0,1,1,1,1,1,0,0,0,0},
                {0,0,0,1,1,1,0,0,0,0,0},
                {0,0,0,0,1,0,0,0,0,0,0},
                {0,0,0,0,0,0,0,0,0,0,0},
        };
        for(int[] data : datas ) {
            for(int value : data) {
                if(value == 0) {
                    System.out.print("  ");
                } else {
                    System.out.print("* ");
                }
            }
            System.out.println(""); // 入れ子になっている配列の展開が終わったら改行
        }


    }
}
実行結果

          * * * * *   
            * * * *   
          * * * * *   
        * * * * * *   
      * * * * *   *   
    * * * * *         
      * * *           
        *             

別に悩むほどのことでもなかったけど、foreachが別のオブジェクトを生成しないと使えないという点は少し不便に感じたし、「それも覚えないといけないのか」と思うとちょっとびっくりしたので、メモ書きとして残しておきます。

1
4
2

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
1
4