List和二維陣列之間轉化及初始化
阿新 • • 發佈:2019-01-01
ArrayList resultsList = new ArrayList(); String[] result = { "cr_tx_amt",(f_fare", "counts" }; resultsList.add(result); String[][] results = new String[resultsList.size()][]; for (int i = 0; i < resultsList.size(); i++) { String[] temp = (String[]) resultsList.get(i); results[i] =new String[temp.length]; System.out.print(temp.length); for (int j = 0; j < temp.length; j++) { results[i][j] = temp[j]; } } return results;
注意:無論是一維陣列還是二維,每一維都必須指定長度,要不然會預設只有一個元素的空間。最好不要初始化為null。
定義一個型別的二維陣列 String[][] a;
定義一維陣列長度 a = new String[i][];
定義二維陣列長度 a[i] = new String[j]
例子:將一個字串的內容分隔,並且放入一個二維陣列中
public class TestToString { public static void main(String[] args) { String s = "0,1;3,6,4;7,1"; String[] a = s.split(";"); double[][] d; d = new double[a.length][]; for(int i=0; i<a.length; i++){ String[] s_num = a[i].split(","); for(int j=0; j<s_num.length; j++){ d[i] = new double[s_num.length]; d[i][j] = Double.parseDouble(s_num[j]); System.out.println("d[" + i + "][" + j +"] = " + d[i][j]); } } }