二維數組可以不初始化列數(第二維)。
下面給出的例子是用兩種不同的方式存儲二維數組并輸出:
1. 這是我們通俗易懂的二維數組存儲方法:
String[][] data = new String[][] {{ "youth", "high", "no", "fair", "no" },{ "youth", "high", "no", "excellent", "no" },{ "middle_aged", "high", "no", "fair", "yes" }, };for (String[] s : data) {for (String str : s)System.out.print(str + "\t");System.out.println();}
輸出結果:
youth high no fair no
youth high no excellent no
middle_aged high no fair yes
2.這是把第二維定義為字符串數組的方法,輸出時需要用到強制字符轉換:
Object[] array = new Object[] {new String[] { "age", "income", "student", "credit_rating","buys_computer" },new String[] { "youth", "high", "no", "fair", "no" },new String[] { "youth", "high", "no", "excellent", "no" },};for (int i = 0; i < array.length; i++) {for (int j = 0; j < ((String[]) array[0]).length; j++)System.out.print(<span style="color:#ff0000;">((String[]) array[i])[j]</span> + "\t");System.out.println();}
輸出結果跟上面一樣。