首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 增強 for 循環在一維與二維數組中的應用詳解

     編輯:Java 相關知識

語法本質

for (元素類型 變量名 : 數組/集合) {
    // 變量直接是元素值,非索引
}

編譯器轉換為迭代器或索引循環,無索引訪問能力,適合只讀遍歷。

一維數組示例

int[] arr = {1, 2, 3};
for (int num : arr) {
    System.out.print(num + " ");  // 1 2 3
}

二維數組示例

int[][] matrix = new int[5][3];  // 5行3列,默認全0

// 外層遍歷行(每行是 int[])
for (int[] row : matrix) {
    // 內層遍歷列(每列是 int)
    for (int val : row) {
        System.out.print(val + " ");
    }
    System.out.println();  // 換行
}

輸出結果

0 0 0 
0 0 0 
0 0 0 
0 0 0 
0 0 0 

完整可運行代碼

import java.util.Scanner;

public class EnhancedForDemo {
    public static void main(String[] args) {
        // 一維
        int[] a = {1, 2, 3};
        System.out.print("一維: ");
        for (int i : a) System.out.print(i + " ");
        System.out.println();
        
        // 二維 — 動態分配
        int[][] arr = new int[5][];
        for (int i = 0; i < 5; i++) {
            arr[i] = new int[3];
        }
        
        System.out.println("二維:");
        for (int[] row : arr) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}

適用與不適用場景

場景推薦原因
只讀遍歷元素✅ 增強 for語法簡潔,無越界風險
需要索引/下標❌ 普通 for增強 for 隱藏索引
遍歷時修改數組結構❌ 普通 for增強 for 會拋 ConcurrentModificationException
反向/跳躍遍歷❌ 普通 for增強 for 只能順序
多維數組逐元素處理✅ 嵌套增強 for代碼可讀性最佳

進階:對象數組遍歷

String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
    System.out.println(name.toUpperCase());
}

// 自定義對象
class Student { String name; int age; }
Student[] students = {new Student("A", 18), new Student("B", 20)};
for (Student s : students) {
    System.out.println(s.name + ":" + s.age);
}

總結

增強 for(for-each)是 JDK 5 引入的語法糖,本質是只讀順序遍歷。一維數組直接獲取元素,二維數組外層獲取行數組、內層獲取元素。記住:需要索引時退回普通 for,純遍歷用增強 for。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved