猿问

用Java初始化多维数组

用Java初始化多维数组

声明多维数组并为其赋值的正确方法是什么?

这就是我所拥有的:

int x = 5;int y = 5;String[][] myStringArray = new String [x][y];myStringArray[0][x] = "a string";myStringArray[0][y] = "another string";


慕无忌1623718
浏览 939回答 3
3回答

至尊宝的传说

Java没有“真”多维数组。例如,arr[i][j][k]等于((arr[i])[j])[k]..换句话说,arr是简单的数组、数组的数组.所以,如果您知道数组是如何工作的,那么您就知道多维数组是如何工作的!声明:int[][][] threeDimArr = new int[4][5][6];或者,在初始化时:int[][][] threeDimArr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };准入:int x = threeDimArr[1][0][1];或int[][] row = threeDimArr[1];字符串表示:Arrays.deepToString(threeDimArr);产量"[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]"

海绵宝宝撒

您可以声明多维数组如下:// 4 x 5 String arrays, all Strings are null// [0] -> [null,null,null,null,null]// [1] -> [null,null,null,null,null]// [2] -> [null,null,null,null,null]// [3] -> [null,null,null,null,null]String[][] sa1 = new String[4][5];for(int i = 0; i < sa1.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// sa1.length == 4&nbsp; &nbsp; for (int j = 0; j < sa1[i].length; j++) {&nbsp; &nbsp; &nbsp;//sa1[i].length == 5&nbsp; &nbsp; &nbsp; &nbsp; sa1[i][j] = "new String value";&nbsp; &nbsp; }}// 5 x 0&nbsp; All String arrays are null// [null]// [null]// [null]// [null]// [null]String[][] sa2 = new String[5][];for(int i = 0; i < sa2.length; i++) {&nbsp; &nbsp; String[] anon = new String[ /* your number here */];&nbsp; &nbsp; // or String[] anon = new String[]{"I'm", "a", "new", "array"};&nbsp; &nbsp; sa2[i] = anon;}// [0] -> ["I'm","in","the", "0th", "array"]// [1] -> ["I'm", "in", "another"]String[][] sa3 = new String[][]{ {"I'm","in","the", "0th", "array"},{"I'm", "in", "another"}};
随时随地看视频慕课网APP

相关分类

Java
我要回答