HomeJava二次元配列の使い方

Javaにおける二次元配列についてと、簡単なサンプルコードを掲載しています。

二次元配列の使い方

二次元配列を定義して、値を取り出す

以下のソースで定義、格納の仕方については 以下のサンプルソースのように、lengthをチェックすることで見えてきます。

String[][] twoArray = new String[][]{
    {"one", "two", "three"},
    {"1st", "2nd", "3rd", "4th", "5th"}};

System.out.println(twoArray.length);
System.out.println(twoArray[0].length);
System.out.println(twoArray[1].length);

上記プログラムを実行すると、System.outで

2
3
5

と出力されます。
具体的に、値を取り出す際は

String[][] twoArray = new String[][]{
    {"one", "two", "three"},
    {"1st", "2nd", "3rd", "4th", "5th"}};

for(int i=0; i<twoArray[0].length; i++) {
    System.out.println(twoArray[0][i]);
}

System.out.println("-------");

for(int i=0; i<twoArray[1].length; i++) {
    System.out.println(twoArray[1][i]);
}

上記プログラムを実行すると、System.outで

one
two
three
-------
1st
2nd
3rd
4th
5th

の順に出力されます。
慣れないと少々難しいです。

注意しないと例外(ArrayIndexOutOfBoundsException)を発生させてしまいます。
JDK1.4以前はGenericsがなかったため
何でもかんでも入れられてしまうListやMapの代わりに用いられることもありましたが
Genericsの恩恵もあり、このように使う機会はなくなっていくでしょう。

使い所としては、二次元配列に慣れたエンジニアが
static finalで定義して、乗数としては使えると思います。
Javaトップへ

ページトップへ

トピックアップ メニュー

トピックアップ リンク

Copyright (C) トピックアップ All Rights Reserved.
inserted by FC2 system