类似于一维数组,二维数组声明定义初始化示例:
int[][] arr = int[5][5];
然后可以对数组进行赋值。
不同于C++,Java存在不规则数组(ragged arrays),即每行的列数可以不等。
int[][] triangleArray = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
};
如果创建新数组, 使用语法new int[5][]
,必须指定第一个索引,语法 new int[][]
是错误的。
例子:
import java.util.Scanner;
import java.io.*;
public class PassTwoDimensionalArray {
public static void main(String[] args) {
int[][] m = getArray(); // Get an array
// Display sum of elements
System.out.println("\nSum of all elements is " + sum(m));
}
public static int[][] getArray() {
Scanner input = new Scanner(System.in);
// Enter array values
int[][] m = new int[3][4];
System.out.println("Enter " + m.length + " rows and "
+ m[0].length + " columns: ");
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[i].length; j++)
m[i][j] = input.nextInt();
return m;
}
public static int sum(int[][] m) {
int result = 0;
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[i].length; j++)
result += m[i][j];
return result;
}
}
运行结果:
Enter 3 rows and 4 columns:
1 2 3 4
0 0 0 0
5 6 7 8
Sum of all elements is 36
以2维数组为例,数组的长度例如上例中的m
,m.length
, 为数组的行数,m[0].length
为第1行的列数。
[1] Introduction to Java Programming chapter 8 multidimensional arrays