多次元とは、1つ以上の次元をもつ配列
一次元配列と多次元配列の違い
一元配列
・要素は線形に並んでる。
・要素へアクセスは1つの添え字で行う。
多次元配列
・一つ以上の次元を持つ配列。
・要素をを表形式やより複雑なデータ構造で表現できる
・要素へのアクセスは二次元配列場合は2つ、三次元以上の場合はそれ以上の添え字が必要になる
例)
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
matrix[0][0]
matrix[1][2]
二次元配列の例
public class MainExample {
public static void main(String[] args) {
// 学生のテストの点数を表す二次元配列
int[][] scores = {
{80, 75, 90},
{85, 70, 85},
{90, 80, 95}
};
// 二次元配列をそのまま出力する
for (int[] studentScores : scores) {
for (int score : studentScores) {
System.out.print(score + "\t");
}
System.out.println();
}
}
}