Java 遍历数组的方式有多种,取决于数组类型和特定需求。基本类型数组可以使用 for 或 while 循环,而对象数组可以使用 for 增强循环或 Arrays.stream()。多维数组需要使用嵌套循环遍历每个元素。

Java 遍历数组方法
Java 提供了多种遍历数组的方法,具体选择取决于特定需求和数组类型。
基本类型数组 (int[]、double[])
<code class="java">for (type variable : array) {
// 执行代码块
}</code>例如:
立即学习“Java免费学习笔记(深入)”;
<code class="java">int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}</code><code class="java">for (type variable : array)
// 执行代码块</code><code class="java">int index = 0;
while (index < array.length) {
// 执行代码块
index++;
}</code>对象数组
<code class="java">for (type variable : array) {
// 执行代码块
}</code><code class="java">for (type variable : array)
// 执行代码块</code>例如:
立即学习“Java免费学习笔记(深入)”;
<code class="java">String[] names = {"John", "Mary", "Bob"};
for (String name : names) {
System.out.println(name);
}</code><code class="java">Arrays.stream(array).forEach(element -> {
// 执行代码块
});</code>多维数组
对于多维数组,需要使用嵌套循环来遍历每个元素。例如:
<code class="java">int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
}
}</code>以上就是java怎么遍历数组的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号