English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此程序中,您将学习不同的技术来用Java打印给定数组的元素。
public class Array { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; for (int element : array) { System.out.println(element); } } }
When the program is run, the output is:
1 2 3 4 5
在上述程序中,for-each循环用于迭代给定数组array。
它访问中的每个元素,并使用println()进行数组打印。
import java.util.Arrays; public class Array { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; System.out.println(Arrays.toString(array)); } }
When the program is run, the output is:
[1, 2, 3, 4, 5]
Dans le programme ci-dessus, la boucle for a été remplacée par une ligne de code avec la fonction Arrays.toString().
As you can see, this provides clean output without any additional code lines.
import java.util.Arrays; public class Array { public static void main(String[] args) { int[][] array = {{1, 2}, {3, 4}, {5, 6, 7}}; System.out.println(Arrays.deepToString(array)); } }
When the program is run, the output is:
[[1, 2], [3, 4], [5, 6, 7]]
In the above program, since each element of the array contains another array, only Arrays.toString() is used to print the address of the elements (nested arrays).
To get numbers from the internal array, we only need another function Arrays.deepToString(). This gives us the numbers1,2and so on, we are looking for.
This function also applies to3多维数组。