Giải thích ý nghĩa vòng for `for (Integer num : list)`

e mới học java có đọc đc đoạn code này

import java.util.Scanner;
import java.util.LinkedList;

public class Solution {
    public static void main(String[] args) {
        /* Create and fill Linked List of Integers */
        Scanner scan = new Scanner(System.in);
        int N = scan.nextInt();
        LinkedList<Integer> list = new LinkedList<>();
        for (int i = 0; i < N; i++) {
            int value = scan.nextInt();
            list.add(value);
        }
        
        /* Perfrom queries on Linked List */
        int Q = scan.nextInt();
        for (int i = 0; i < Q; i++) {
            String action = scan.next();
            if (action.equals("Insert")) {
                int index = scan.nextInt();
                int value = scan.nextInt();
                list.add(index, value);
            } else { // "Delete"
                int index = scan.nextInt();
                list.remove(index);
            }
        }
        scan.close();
        
        /* Print our updated Linked List */
        for (Integer num : list) {
            System.out.print(num + " ");
        }
    }
}

E thực sự k hiểu đoạn code in ra linklist mới

for (Integer num : list)

Ai giải thích giúp e với ạ. Em cảm ơn

Đây là 1 cách rút gọn vòng lặp for của java thôi bạn.
Ví dụ:

int[] num = {1, 2, 3};
//Cach 1
for(int i = 0; i<num.length;i++){
	System.out.print(num[i] + " ") ;
}
//Cach 2
for(int i: num) {
	System.out.print(i + " ") ;
} 
4 Likes

Mảng (array) và những lớp triển khai của Iterable<T> sẽ dùng được cú pháp này.
Từ Java 7 về trước thì chỉ dùng với lệnh foreach, Java 8 trở đi thì dùng với for.

4 Likes

Cái này là for-each được thêm vào từ Java 5, gọi lại enhanced for loop.

3 Likes

java làm gì có keyword foreach hay lệnh foreach. Từ java 5 trở đi là dùng for each được với kiểu iterable thông qua cú pháp for thôi.

4 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?