LoginSignup
0
1

More than 3 years have passed since last update.

Javaでの配列のしくみ(図解)

Last updated at Posted at 2019-09-04

配列

配列とは、データを並べて入れておく箱を準備して、出し入れをする表現です。
配列には一次元配列と多次元配列というものがあります。
例題を使いながら、配列の仕組みを説明していきます。

一次元配列

配列の各要素に1,2,3,4,5を代入して表示してみましょう

Array1

class Array {
    public static void main(String[] args) {

        int[] a = new int[5];

        for (int i = 0; i < a.length; i++){
            a[i] = i + 1;
        }

        for (int i = 0; i < a.length; i++){
            System.out.println("a[" + i + "] = " + a[i]);
        }
    } 
}
【実行結果】
a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=5

Qiita用_配列1.PNG

多次元配列

配列の各要素に1,2,3,4,1,2,3,4を代入して表示してみましょう

Array2
class A2 {
    public static void main(String[] args) {

            int[][] x = new int[2][4];

            for (int i = 0; i < 2; i++) {
                for (int j = 0; j < 4; j++) {
                    x[i][j] = j + 1;
                    System.out.println("x[" + i + "][" + j + "] = " + x[i][j]);
                }
            }
    } 
} 
【実行結果】
x[0][0] = 1
x[0][1] = 2
x[0][2] = 3
x[0][3] = 4
x[1][0] = 1
x[1][1] = 2
x[1][2] = 3
x[1][3] = 4

Qiita用_配列2.PNG

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