Home >Java >Javagetting Started >How to optimize the output form of arrays in java
One-dimensional array:
Define an array:
int[] array = { 1, 2, 3, 4, 5 };
(1) Traditional for loop method, sample code 1:
for (int i = 0; i < array.length; i++) { System.out.println(array[i]); }
(Free learning video tutorial sharing: java video tutorial)
Output result:
(2) for each loop, sample code 2:
for (int a : array) { System.out.println(a); }
Output result:
(3) Using Arrays toString method in the class, sample code 3:
System.out.println(array);// 这样打印的是数组的首地址。 System.out.println(Arrays.toString(array));
Output result:
Two-dimensional array:
These three methods also correspond to two-dimensional arrays. Define a two-dimensional array:
int[][] arrays = { { 16, 3, 2, 13 }, { 5, 10, 11, 8 }, { 9, 6, 7, 3 } };
Java actually does not have multi-dimensional arrays, only one-dimensional arrays. Multi-dimensional arrays are interpreted as "Array of arrays", for example, the two-dimensional array arrays is a one-dimensional array containing three elements {arrays[0], arrays[1], arrays[2]}, arrays[0] is a one-dimensional array containing {16,3,2, 13} A one-dimensional array of four elements, the same goes for arrays[1] and arrays[2].
(1) Traditional for loop method, sample code 1:
for (int i = 0; i < arrays.length; i++) { for (int j = 0; j < arrays[i].length; j++) { System.out.print(arrays[i][j] + " "); } System.out.println(); // 换行 }
Output result:
(2) for each loop , Sample code 2:
for (int[] a : arrays) { for (int b : a) { System.out.print(b + " "); } System.out.println();// 换行 }
Output result:
(3) Use the toString method in the Arrays class, Sample code 3:
for (int i = 0; i < arrays.length; i++) { System.out.println(Arrays.toString(arrays[i])); }
Output results:
Recommended related articles and tutorials: java introductory tutorial
The above is the detailed content of How to optimize the output form of arrays in java. For more information, please follow other related articles on the PHP Chinese website!