java - 基础 - 二维数组
声明:
int[][] array;
初始化
静态: int[][] array = { {1,2,3}, {2,3,4}, {10,20,30}};
动态: int[][] array = new int[2][3];
遍历:
import java.util.*; class test{ public static void main(String[] args){ int[][] a = new int[][]{{1,2},{3,4},{5}}; int[][] b = {{10,20},{30},{40,50}}; String[][] c;//定义和初始化分开时必须有new c = new String[][]{{"a","b"},{"c","d"},{"e"}}; //遍历和一维数组类似 System.out.println("-----a-----"); for(int i = 0; i < a.length; i++){ for(int j = 0; j < a[i].length; j++){ System.out.println(a[i][j]); } } System.out.println("-----b-----"); for(int[] e1:b){ for(int e2:e1){ System.out.println(e2); } } System.out.println("-----c-----"); for(String[] e1:c){ for(String e2:e1){ System.out.println(e2); } } } }
int[][] a = new int[3][]; //可以编译运行,但是如果使用如a[0][0]会报空指针异常,此时a[0][0]是空
a[0] = new int[2];
a[1] = new int[2];
a[2] = new int[1];